如何使用 C# 获取 .NET 中的格式化 JSON?
使用 命名空间 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"}
广告