如何用C#美化JSON?我想在TextBox控件中打印结果。
是否可以使用JavaScriptSerializer,或者我应该使用JSON.net?除非迫不得已,否则我希望避免对字符串进行反序列化。
发布于 2015-04-13 01:26:12
使用JSON.Net,您可以使用特定的格式来美化输出。
Demo on 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"
]
}
发布于 2021-03-12 01:54:00
您可以在不使用新的System.Text.Json名称空间反序列化的情况下处理JSON,以避免添加对json.NET的依赖。
using System.IO;
using System.Text;
using System.Text.Json;
public static string BeautifyJson(string json)
{
using JsonDocument document = JsonDocument.Parse(json);
using var stream = new MemoryStream();
using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions() { Indented = true });
document.WriteTo(writer);
writer.Flush();
return Encoding.UTF8.GetString(stream.ToArray());
}
The docs have more examples of how to use the low-level types in the namespace.
发布于 2020-03-18 21:57:24
ShouldSerializeContractResolver.cs
public class ShouldSerializeContractResolver : DefaultContractResolver
{
public static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
return property;
}
}
var beautifyJson= Newtonsoft.Json.JsonConvert.SerializeObject(data, new JsonSerializerSettings()
{
ContractResolver = ShouldSerializeContractResolver.Instance,
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented
});
你可以用上面的代码美化json。
https://stackoverflow.com/questions/6178544
复制相似问题