The default ident in Json.Net seems to be 2 spaces:
var result = JsonConvert.SerializeObject(jsonString, Formatting.Indented);
For clarity I want to change it to 4 spaces, but I don't seem to find the right way to apply the property. It seems that it exists, since I have found some similar code (direct link here):
using (JsonTextWriter jw = new JsonTextWriter(sw))
{
jw.Formatting = Formatting.Indented;
jw.IndentChar = ' ';
jw.Indentation = 4;
jw.WriteRaw(config.ToString());
}
...except that, if possible, I would preffer to avoid having to unnecessarily deal with streams in this case.
Any suggestion?
I would create a utility class which serializes it with the right indentation, similar to how JsonConvert.SerializeObject
does it:
public static class JsonConvertEx
{
public static string SerializeObject<T>(T value)
{
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
var jsonSerializer = JsonSerializer.CreateDefault();
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.IndentChar = ' ';
jsonWriter.Indentation = 4;
jsonSerializer.Serialize(jsonWriter, value, typeof(T));
}
return sw.ToString();
}
}
And consume it like this:
class Program
{
static void Main(string[] args)
{
var anon = new { Name = "Yuval", Age = 1 };
var result = JsonConvertEx.SerializeObject(anon);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With