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