注意:我使用的System.Text.Json
不是JSON.NET
已经回答了类似的问题。我需要相同的答案,但对于System.Text.Json
. 我想将我的课程写成 Json 并确保它是人类可读的。为此,我在选项中将缩进设置为 true。但是,该类包含一个List<double>
我不想缩进的属性,因为它使文件很长。
所以我有这个:
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);
我希望它像这样序列化:
{
"Name": "Example",
"LargeList ": [0,0,0]
}
不是这个(或类似的东西):
{
"Name": "Example",
"LargeList ": [
0,
0,
0
]
}
我写了一个JsonConverter
来实现这一点:
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);
}
}
但是,这会将数组写入我并不真正想要的字符串。最好的方法是什么?
即你得到“[1,2,3]”而不是[1,2,3]
其次,writer
传递给Write
函数的对象具有Options
属性,但不能更改。因此,如果我使用 writer 对象手动写出数组,它会缩进。