使用命名空间Newtonsoft.Json.Formatting Newtonsoft.Json.Formatting提供了用于格式化Json的格式化选项
None - 不应用特殊格式。这是默认值。
Indented -使子对象根据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"}