Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating JSON without array indentation

Tags:

json

c#

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

like image 678
Dakson Avatar asked Oct 20 '25 08:10

Dakson


1 Answers

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

like image 130
Brian Rogers Avatar answered Oct 22 '25 03:10

Brian Rogers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!