简体   繁体   中英

How can I beautify JSON for display in a TextBox?

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? Unless I have to, I'd like to avoid deserializing the string.

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

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

Edit: following up on the discussion in the comments about performance, I measured using BenchMark.Net and there is an extra allocation cost using JToken.Parse , and a very small increase in time taken:

在此处输入图像描述

Benchmark code

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

You can process JSON without deserializing using the new System.Text.Json namespace, to avoid adding a dependency on json.NET. This is admittedly not as terse as 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.

For those who ask how I get formatted JSON in .NET using C# and want to see how to use it right away and one-line lovers . Here are the indented JSON string one-line codes:

There are 2 well-known JSON formatter or parsers to serialize:

Newtonsoft Json.Net version:

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(yourObj, Formatting.Indented);

.Net 7 version:

using System.Text.Json;

var jsonString = JsonSerializer.Serialize(yourObj, new JsonSerializerOptions { WriteIndented = true });
string formattedJson = System.Text.Json.Nodes.JsonNode.Parse(json).ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM