ใช้ เนมสเปซ Newtonsoft.Json.Formatting Newtonsoft.Json.Formatting ให้ตัวเลือกการจัดรูปแบบเพื่อจัดรูปแบบ Json
ไม่มี - ไม่ใช้การจัดรูปแบบพิเศษ นี่คือค่าเริ่มต้น
เยื้อง − ทำให้วัตถุย่อยถูกเยื้องตามการตั้งค่า Newtonsoft.Json.JsonTextWriter.Indentation และ Newtonsoft.Json.JsonTextWriter.IndentChar
ตัวอย่าง
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" }
};
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; }
} ผลลัพธ์
{
"Sizes": [
"Small",
"Medium",
"Large"
],
"Price": 3.9900,
"Expiry": "2008-12-28T00:00:00",
"Name": "Apple"
} ตัวอย่าง
static class Program{
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" }
};
string json = JsonConvert.SerializeObject(product, Formatting.None);
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; }
} ผลลัพธ์
{"Sizes":["Small","Medium","Large"],"Price":3.9900,"Expiry":"2008-12-28T00:00:00","Name":"Apple"}