Search code examples
c#jsonserializationjson.net

Is there a way to use a custom indentation character with the Json.Net JsonSerializer?


I need to change the way the JsonSerializer indents to use tabs instead of 2 spaces... Is this possible?

I can turn indentation on as described here.

My code looks something like this:

var jsonSerializer = new JsonSerializer
{
    Formatting = Newtonsoft.Json.Formatting.Indented
};

using (var fs = File.Create(fileName))
using (var sw = new StreamWriter(fs))
{
    jsonSerializer.Serialize(sw, data);
}

Note: this is a different question to this one describes a method with the JsonTextWriter - I want to do it with JsonSerializer if possible.


Solution

  • Check out a custom JsonWriter.

    using (var fs = File.Create("data.json"))
    using (var sw = new StreamWriter(fs))
    using (var jtw = new JsonTextWriter(sw) { 
      Formatting= Formatting.Indented, 
      Indentation=3, 
      IndentChar = '\t'}) {
      (new JsonSerializer()).Serialize(jtw, data);
    }