Serialize/Deserialize System.Drawing.Color 和 System.Text.Json

Serialize/Deserialize System.Drawing.Color with System.Text.Json

问题是 serialize/deserialize class 和 ColorSystem.Drawing.ColorSystem.Text.Json

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());
}

有了转换器,serialization/deserilization 工作正常。

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]