67

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.

Omer
  • 8,194
  • 13
  • 74
  • 92
Stefan
  • 1,486
  • 2
  • 13
  • 19
  • 1
    You mean format it with newlines and indentation? – Seth Carnegie May 30 '11 at 16:19
  • 2
    Could this be a possible duplicate? http://stackoverflow.com/questions/4580397/json-formatter-in-c – Seth Carnegie May 30 '11 at 16:22
  • Do you want to format your JSON code so that it looks nice and readable? But what formatting JSON code has to do with deserialization? – FIre Panda May 30 '11 at 16:22
  • yes, i'm talking about beautifying, newlines, indentation. I do not want/need to deserialize anything, i just thaught that if i'm using JSON.Net i have to deserialize=>serialize in order to have a pretty json output. – Stefan May 31 '11 at 06:41

6 Answers6

56

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:

enter image description here

Benchmark code

stuartd
  • 70,509
  • 14
  • 132
  • 163
  • 1
    When you parse to create a JToken, arent you create a dynamic object? – aloisdg May 30 '18 at 08:41
  • 1
    @aloisdg probably, yes. – stuartd May 30 '18 at 09:22
  • I will have to check for performance issue. I am not sure that we are winning here. – aloisdg May 30 '18 at 09:34
  • 1
    The [docs](https://www.newtonsoft.com/json/help/html/Performance.htm) say _"The absolute fastest way to read and write JSON is to use JsonTextReader/JsonTextWriter directly to manually serialize types"_ but for most use cases involving formatting Json that's not necessary, and [a lot more effort](https://www.newtonsoft.com/json/help/html/ReadingWritingJSON.htm). – stuartd May 30 '18 at 10:27
48

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"
  ]
}
aloisdg
  • 22,270
  • 6
  • 85
  • 105
  • 5
    I assume the reason why this wasnt accepted as the answer is because, beautifying the JSON using this method would require deserialization first before re-serialization? – Jimbo May 22 '17 at 07:41
  • @Jimbo Indeed. I will check for an alternative. You can also look for stuartd [answer](https://stackoverflow.com/a/48153713/1248177) – aloisdg May 30 '18 at 09:35
6

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.

RedMatt
  • 476
  • 5
  • 9
3

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

RidvanC
  • 61
  • 11
2
string formattedJson = System.Text.Json.Nodes.JsonNode.Parse(json).ToString();
Andy
  • 578
  • 4
  • 6
  • 1
    This was my solution. Thanks! So simple and it turned my JSON string into a readable self-formatted display in Chrome and Firefox. – Fandango68 Jun 09 '23 at 02:47
1

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

Newtonsoft Json.Net version:

using Newtonsoft.Json;

dynamic parsedJson = JsonConvert.DeserializeObject(unPrettyJson);
var prettyJson = JsonConvert.SerializeObject(parsedJson, Formatting.Indented);

.Net 7 version:

using System.Text.Json;

var jsonElement = JsonSerializer.Deserialize<JsonElement>(unPrettyJson);
var prettyJson = JsonSerializer.Serialize(jsonElement , new JsonSerializerOptions { WriteIndented = true });
Omer
  • 8,194
  • 13
  • 74
  • 92
  • The .NET 7 version is not actually working when `yourObj` is a JSON string object as the result will have all the special characters like "{" encoded, while the answer bellow that use `System.Text.Json.Nodes.JsonNode.Parse(json).ToString()` do it right. – Sevenate Mar 07 '23 at 03:39
  • @Sevenate, please see the updated version, and if it works please upvote. Happy coding... – Omer Mar 07 '23 at 06:03