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.
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.
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.
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.
DefaultIgnoreCondition Property (System. Text. Json) Gets or sets a value that determines when properties with default values are ignored during serialization or deserialization.
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);
}
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