Reputation: 75
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?
Optimal case is:
Upvotes: 4
Views: 1573
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