How can I beautify JSON for display in a TextBox?

六眼飞鱼酱① 提交于 2019-11-29 04:40:33

问题


How can I beautify JSON with C#? I want to print the result in a TextBox control.

Is it possible to use JavaScriptSerializer for this, or should I use JSON.net? Unless I have to, I'd like to avoid deserializing the string.


回答1:


With JSON.Net you can beautify the output with a specific formatting.

Demo on dotnetfiddle.

Code

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);
}

Output

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



回答2:


Bit late to this party, but you can beautify (or minify) Json without deserialization using json.NET:

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


来源:https://stackoverflow.com/questions/6178544/how-can-i-beautify-json-for-display-in-a-textbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!