Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 962
JaySeeAre Avatar asked Aug 19 '16 09:08

JaySeeAre


People also ask

What is Newtonsoft JSON formatting indented?

Use Namespace Newtonsoft.Json.Formatting Newtonsoft.Json.Formatting provides formatting options to Format the Json. None − No special formatting is applied. This is the default. Indented − Causes child objects to be indented according to the Newtonsoft.

Is Newtonsoft JsonSerializer thread safe?

Correct, JsonSerializer is threadsafe. No state is shared while serializing but if you change a setting on the JsonSerializer while in the middle of serializing an object then those will automatically be used.

What is Jsonproperty attribute?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.

What is Jsonserializersettings?

DefaultIgnoreCondition Property (System. Text. Json) Gets or sets a value that determines when properties with default values are ignored during serialization or deserialization.


1 Answers

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);
}
like image 185
andrei.ciprian Avatar answered Sep 18 '22 01:09

andrei.ciprian