Reputation: 821
The problem was to serialize/deserialize a class with Color
from System.Drawing.Color
with System.Text.Json
.
public class Test
{
public Color Farbe { get; set; }
public IEnumerable<Color> Farben { get; set; }
}
Serialization
File.WriteAllText("data.json", JsonSerializer.Serialize(test));
without any converters the serialized json file looks like this:
{
"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"
}
]
}
Deserialisation is not possible. The result will be empty:
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));
Result
0:0:0
Color [Empty],Color [Empty],Color [Empty]
Upvotes: 4
Views: 2334
Reputation: 821
After some searching i found a solution and get a converter for 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());
}
With the converter, serialization/deserilization is working proper.
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));
Result
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]
Upvotes: 13