Dakson
Dakson

Reputation: 75

Creating JSON without array indentation

I usually get very big JSON with a lot of lists and a lot of elements inside the lists. My goal is to get the left structure instead of the right one. The right structure is what I get from Newtonsoft. Is there another library that gives me the control to print it like this?

enter image description here

Optimal case is:

enter image description here

Upvotes: 4

Views: 1573

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129787

You can get the indenting you want with Json.Net (a.k.a. Newtonsoft Json) if you subclass the JsonTextWriter class and override the WriteIndent method like this:

public class CustomJsonTextWriter : JsonTextWriter
{
    public CustomJsonTextWriter(TextWriter writer) : base(writer)
    {
    }

    protected override void WriteIndent()
    {
        if (WriteState != WriteState.Array)
            base.WriteIndent();
        else
            WriteIndentSpace();
    }
}

Then create a small helper method to make it easy to use the custom writer:

public static class JsonHelper
{
    public static string SerializeWithCustomIndenting(object obj)
    {
        using (StringWriter sw = new StringWriter())
        using (JsonWriter jw = new CustomJsonTextWriter(sw))
        {
            jw.Formatting = Formatting.Indented;
            JsonSerializer ser = new JsonSerializer();
            ser.Serialize(jw, obj);
            return sw.ToString();
        }
    }
} 

Here is a working demo: https://dotnetfiddle.net/RusBGI

Upvotes: 8

Related Questions