用System.Text.Json序列化/反序列化System.Drawing.Color



问题是用System.Text.JsonSystem.Drawing.Color序列化/反序列化一个具有Color的类

public class Test
{
public Color Farbe { get; set; }
public IEnumerable<Color> Farben { get; set; }
}

序列化
File.WriteAllText("data.json", JsonSerializer.Serialize(test));

如果没有任何转换器,序列化的json文件看起来像这样:

{
"Farbe": {
"R": 255,
"G": 0,
"B": 0,
"A": 255,
"...": "...",
"Name":" Red"
},
"Farben": [
{
"R":255,
"G":0,
"B":0,
"A":255,
"...": "...",
"Name":"Red"
},
{
"R":0,
"G":128,
"B":0,
"A":255,
"...": "...",
"Name":"Green"
}
]
}

不可能反序列化。结果将为空:

Test test2 = JsonSerializer.Deserialize<Test>(File.ReadAllText("data.json"));
Console.WriteLine($"{test2.Farbe.R}:{test2.Farbe.G}:{test2.Farbe.B}");
Console.WriteLine(string.Join(',', test2.Farben));

结果

0:0:0
Color [Empty],Color [Empty],Color [Empty]

经过一番搜索,我找到了一个解决方案,并获得了System.Drawing.Color的转换器:

public class ColorJsonConverter : JsonConverter<Color>
{
public override Color Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => ColorTranslator.FromHtml(reader.GetString());
public override void Write(Utf8JsonWriter writer, Color value, JsonSerializerOptions options) => writer.WriteStringValue("#" + value.R.ToString("X2") + value.G.ToString("X2") + value.B.ToString("X2").ToLower());
}

使用转换器,序列化/反序列化工作正常。

Test test = new()
{
Farbe = Color.Red,
Farben = new List<Color>()
{
Color.Red,
Color.Green,
Color.Blue
}
};
var options = new JsonSerializerOptions()
{
Converters = {
new ColorJsonConverter()
}
};
File.WriteAllText("data.json", JsonSerializer.Serialize(test, options));
Test test2 = JsonSerializer.Deserialize<Test>(File.ReadAllText("data.json"), options);
Console.WriteLine($"{test2.Farbe.R}:{test2.Farbe.G}:{test2.Farbe.B}");
Console.WriteLine(string.Join(',', test2.Farben));

结果

255:0:0
Color [A=255, R=255, G=0, B=0],Color [A=255, R=0, G=128, B=0],Color [A=255, R=0, G=0, B=255]

相关内容

  • 没有找到相关文章

最新更新