Newtonsoft.Json.Formatting एनम JSON को फॉर्मेट करने के विकल्प प्रदान करता है:
- None - कोई विशेष फॉर्मेटिंग लागू नहीं। यह डिफ़ॉल्ट है।
- Indented - चाइल्ड ऑब्जेक्ट्स को
JsonTextWriter.IndentationऔरJsonTextWriter.IndentCharसेटिंग्स के अनुसार इंडेंट करता है।
उदाहरण 1: इंडेंटेड JSON (पठनीय)
using Newtonsoft.Json;
static void Main(string[] args)
{
Product product = new Product
{
Name = "Apple",
Expiry = new DateTime(2008, 12, 28),
Price = 3.9900M,
Sizes = new[] { "Small", "Medium", "Large" }
};
// Indented फॉर्मेटिंग
string json = JsonConvert.SerializeObject(product, Formatting.Indented);
Console.WriteLine(json);
// डिसीरियलाइज़ेशन
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
Console.ReadLine();
}
class Product
{
public String[] Sizes { get; set; }
public decimal Price { get; set; }
public DateTime Expiry { get; set; }
public string Name { get; set; }
}
आउटपुट (Indented)
{
"Sizes": [
"Small",
"Medium",
"Large"
],
"Price": 3.9900,
"Expiry": "2008-12-28T00:00:00",
"Name": "Apple"
}
उदाहरण 2: कॉम्पैक्ट JSON (कोई इंडेंटेशन नहीं)
static void Main(string[] args)
{
Product product = new Product
{
Name = "Apple",
Expiry = new DateTime(2008, 12, 28),
Price = 3.9900M,
Sizes = new[] { "Small", "Medium", "Large" }
};
// None फॉर्मेटिंग (कॉम्पैक्ट)
string json = JsonConvert.SerializeObject(product, Formatting.None);
Console.WriteLine(json);
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
Console.ReadLine();
}
आउटपुट (None/Compact)
{"Sizes":["Small","Medium","Large"],"Price":3.9900,"Expiry":"2008-12-28T00:00:00","Name":"Apple"}
उन्नत फॉर्मेटिंग विकल्प
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore, // null मानों को अनदेखा करें
DefaultValueHandling = DefaultValueHandling.Ignore, // डिफ़ॉल्ट मानों को अनदेखा करें
ContractResolver = new CamelCasePropertyNamesContractResolver(), // camelCase प्रॉपर्टी नाम
DateFormatString = "yyyy-MM-dd" // कस्टम डेट फॉर्मेट
};
string json = JsonConvert.SerializeObject(product, settings);
System.Text.Json (.NET Core 3.0+) का उपयोग
using System.Text.Json;
var options = new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
string json = JsonSerializer.Serialize(product, options);