JSON formatter in C#?

You could also use the Newtonsoft.Json library for this and call SerializeObject with the Formatting.Indented enum –

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

Documentation: Serialize an Object


Update –

Just tried it again. Pretty sure this used to work – perhaps it changed in a subsequent version or perhaps i’m just imagining things. Anyway, as per the comments below, it doesn’t quite work as expected. These do, however (just tested in linqpad). The first one is from the comments, the 2nd one is an example i found elsewhere in SO –

void Main()
{
    //Example 1
    var t = "{\"x\":57,\"y\":57.0,\"z\":\"Yes\"}";
    var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(t); 
    var f = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
    Console.WriteLine(f);

    //Example 2
    JToken jt = JToken.Parse(t);
    string formatted = jt.ToString(Newtonsoft.Json.Formatting.Indented);
    Console.WriteLine(formatted);

    //Example 2 in one line -
    Console.WriteLine(JToken.Parse(t).ToString(Newtonsoft.Json.Formatting.Indented));
}

Leave a Comment