如何美化JSON以在TextBox中显示?

如何用C#美化JSON? 我想在TextBox控件中打印结果。

是否可以使用JavaScriptSerializer,或者我应该使用JSON.net? 除非我必须,否则我想避免反序列化字符串。

使用JSON.Net,您可以使用特定格式美化输出。

在dotnetfiddle上演示 。

public class Product { public string Name {get; set;} public DateTime Expiry {get; set;} public string[] Sizes {get; set;} } public void Main() { Product product = new Product(); product.Name = "Apple"; product.Expiry = new DateTime(2008, 12, 28); product.Sizes = new string[] { "Small" }; string json = JsonConvert.SerializeObject(product, Formatting.None); Console.WriteLine(json); json = JsonConvert.SerializeObject(product, Formatting.Indented); Console.WriteLine(json); } 

产量

 {"Name":"Apple","Expiry":"2008-12-28T00:00:00","Sizes":["Small"]} { "Name": "Apple", "Expiry": "2008-12-28T00:00:00", "Sizes": [ "Small" ] } 

这个派对迟到了,但是你可以使用json.NET在没有反序列化的情况下美化(或缩小)Json:

 JToken parsedJson = JToken.Parse(jsonString); var beautified = parsedJson.ToString(Formatting.Indented); var minified = parsedJson.ToString(Formatting.None);