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

时间:2011-05-30 16:15:59

标签: c# json

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

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

4 个答案:

答案 0 :(得分:31)

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

在dotnetfiddle上

Demo

代码

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"
  ]
}

答案 1 :(得分:13)

这个派对迟到了,但你可以美化(或缩小)Json而不使用json.NET进行反序列化:

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

答案 2 :(得分:2)

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

答案 3 :(得分:1)

您可以使用新的 System.Text.Json 命名空间在不反序列化的情况下处理 JSON,以避免添加对 json.NET 的依赖。诚然,这不像 stuartd's simple answer 那样简洁:

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.