[英]How can I beautify JSON for display in a TextBox?
怎么把JSON美化成C#? 我想在 TextBox 控件中打印結果。
是否可以為此使用 JavaScriptSerializer,或者我應該使用 JSON.net? 除非必須,否則我想避免反序列化字符串。
使用JSON.Net ,您可以使用特定格式美化 output。
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);
}
Output
{"Name":"Apple","Expiry":"2008-12-28T00:00:00","Sizes":["Small"]}
{
"Name": "Apple",
"Expiry": "2008-12-28T00:00:00",
"Sizes": [
"Small"
]
}
這個聚會有點晚了,但你可以美化(或縮小)Json,而無需使用 Json.NET 進行反序列化:
JToken parsedJson = JToken.Parse(jsonString);
var beautified = parsedJson.ToString(Formatting.Indented);
var minified = parsedJson.ToString(Formatting.None);
編輯:跟進評論中關於性能的討論,我使用BenchMark.Net進行了測量,使用JToken.Parse
會產生額外的分配成本,並且花費的時間增加非常小:
應該SerializeContractResolver.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
您可以使用新的 System.Text.Json 命名空間處理 JSON 而無需反序列化,以避免添加對 json.NET 的依賴。 誠然,這不像stuartd 的簡單回答那樣簡潔:
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());
}
對於那些問我如何使用 C# 將 JSON 格式化為 .NET 並想立即查看如何使用它的人和在線愛好者。 以下是縮進的 JSON 字符串單行代碼:
有 2 個著名的 JSON 格式化程序或解析器可以序列化:
using Newtonsoft.Json;
var jsonString = JsonConvert.SerializeObject(yourObj, Formatting.Indented);
using System.Text.Json;
var jsonString = JsonSerializer.Serialize(yourObj, new JsonSerializerOptions { WriteIndented = true });
string formattedJson = System.Text.Json.Nodes.JsonNode.Parse(json).ToString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.