How can I beautify JSON for display in a TextBox?

后端 未结 3 519
北海茫月
北海茫月 2020-12-29 01:06

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? Un

相关标签:
3条回答
  • 2020-12-29 01:35

    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"
      ]
    }
    
    0 讨论(0)
  • 2020-12-29 01:48

    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);
    
    0 讨论(0)
  • 2020-12-29 01:51

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

    you can beautify json with above code

    0 讨论(0)
提交回复
热议问题