NB: I am using System.Text.Json
not JSON.NET
for which there is similar question that has been answered. I need the same answer but for System.Text.Json
. I would like to write my class to Json and ensure that it is human readable. To do this I have set the indent to true in options. However, the class contains a List<double>
property which I don't want to indent as it makes the file very long.
So I have this:
public class ThingToSerialize
{
public string Name {get;set;}
//other properties here
public List<double> LargeList {get;set;}
};
var thing = new ThingToSerialize {Name = "Example", LargeList = new List<double>{0,0,0}};
var options = new JsonSerializerOptions
{
WriteIndented = true
};
options.Converters.Add(new DontIndentArraysConverter());
var s = JsonSerializer.Serialize(thing, options);
and I want it to serialize like this:
{
"Name": "Example",
"LargeList ": [0,0,0]
}
Not this (or something along these lines):
{
"Name": "Example",
"LargeList ": [
0,
0,
0
]
}
I have written a JsonConverter
to achieve this:
public class DontIndentArraysConverter : JsonConverter<List<double>>
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(List<double>);
}
public override List<double> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return JsonSerializer.Deserialize<List<double>>(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, List<double> value, JsonSerializerOptions options)
{
var s = JsonSerializer.Serialize(value);
writer.WriteStringValue(s);
}
}
However this writes the array as a string which I don't really want. Whats the best approach for this?
i.e. you get "[1,2,3]" instead of [1,2,3]
Secondly, the writer
object that is passed into the Write
function has an Options
property but this cannot be changed. So if I write the array out manually using the writer object, it is indented.