How can I beautify JSON with C#? I want to print the result in a TextBox control.
如何用c#美化JSON ?我想在文本框控件中打印结果。
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.
是否可以为此使用JavaScriptSerializer,还是应该使用JSON.net?除非必要,否则我希望避免对字符串进行反序列化。
2 个解决方案
#1
30
With JSON.Net you can beautify the output with a specific formatting.
与JSON。Net可以使用特定的格式美化输出。
Demo on dotnetfiddle.
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
6
Bit late to this party, but you can beautify (or minify) Json without deserialization using json.NET:
虽然有点晚了,但是您可以使用json.NET美化(或缩小)Json而不用反序列化:
JToken parsedJson = JToken.Parse(jsonString);
var beautified = parsedJson.ToString(Formatting.Indented);
var minified = parsedJson.ToString(Formatting.None);
#1
30
With JSON.Net you can beautify the output with a specific formatting.
与JSON。Net可以使用特定的格式美化输出。
Demo on dotnetfiddle.
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
6
Bit late to this party, but you can beautify (or minify) Json without deserialization using json.NET:
虽然有点晚了,但是您可以使用json.NET美化(或缩小)Json而不用反序列化:
JToken parsedJson = JToken.Parse(jsonString);
var beautified = parsedJson.ToString(Formatting.Indented);
var minified = parsedJson.ToString(Formatting.None);