I am trying to serialize this dictionary:
IDictionary<string, ResetableObjectTheme> ResetableObjectThemes = new Dictionary<string, ResetableObjectTheme>()
{
{"ThemeDark", new ResetableObjectTheme() { ResetablePatternObject = new PatternObject(), ResetableMaterialObject = new MaterialObject()}},
{"ThemeLight", new ResetableObjectTheme() { ResetablePatternObject = new PatternObject(), ResetableMaterialObject = new MaterialObject()}},
};
string json = System.Text.Json.JsonSerializer.Serialize(ResetableObjectThemes, new JsonSerializerOptions() { WriteIndented = true });
After that I get a wrong result string json, like this:
{
"ResetableObjectThemes": {
"ThemeDark": {
"ResetablePatternObject": {},
"ResetableMaterialObject": {}
},
"ThemeLight": {
"ResetablePatternObject": {},
"ResetableMaterialObject": {}
}
}
}
But it should be something like this:
{
"ResetableObjectThemes": {
"ThemeDark": {
"ResetablePatternObject": {
"Thickness": 3,
"BoundaryColor": {
"ColorContext": null,
"A": 255,
"R": 0,
"G": 0,
"B": 128,
},
},
"ResetableMaterialObject": {
"BoundaryThickness": 3,
"BoundaryColor": {
"ColorContext": null,
"A": 255,
"R": 0,
"G": 0,
"B": 255,
},
}
},
"ThemeLight": {
"ResetablePatternObject": {
"Thickness": 3,
"BoundaryColor": {
"ColorContext": null,
"A": 255,
"R": 0,
"G": 0,
"B": 128,
},
},
"ResetableMaterialObject": {
"BoundaryThickness": 3,
"BoundaryColor": {
"ColorContext": null,
"A": 255,
"R": 0,
"G": 0,
"B": 255,
},
}
}
}
}
The classes are:
public class ResetableObjectTheme
{
public ResetableBaseObject ResetablePatternObject { get; set; } = new PatternObject();
public ResetableBaseObject ResetableMaterialObject { get; set; } = new MaterialObject();
}
public class PatternObject : ResetableBaseObject
{
public double Thickness { get; set; } = 1;
public Color BoundaryColor { get; set; } = Colors.Blue;
}
public class MaterialObject : ResetableBaseObject
{
public double BoundaryThickness { get; set; } = 3;
public Color BoundaryColor { get; set; } = Colors.Blue;
}
and ResetableBaseObject is just a base class containing a common method. I had already using this approach for another stuff where instead of type ResetableBaseObject, were used an enumeration and the serialization/deserialization worked perfectly. The reason for using a dictionary is that this way I can dynamically set values according to some UI theme:
ResetableObjectThemes[ThemeManager.CurrentTheme].ResetablePatternObject = new PatternObject() { Thickness = 5.5 };
Why is System.Text.Json.JsonSerializer.Serialize/Deserialize not able to do the job for nested non-enum types?