2

I'm trying to serialize and deserialize a complex object tree, with some objects requiring a custom JsonConverter. It's easy to apply such a converter to object properties where the property is a simple object, but I don't know how to apply one in cases where the property is a collection.

For example:

[JsonObject(MemberSerialization.OptIn)]
public class Settings
{
    [JsonProperty] public Dictionary<string, Color> ColorSet;
    [JsonProperty, JsonConverter(typeof(ColorConverter))] public Color CurrentColor;
}

Color is a type requiring its own JsonConverter (fyi: this is Xamarin.Forms.Color, which does not deserialize from Json out of the box).

Using

Settings newSettings = JsonConvert.DeserializeObject<Settings>(jsondata);

results in a new Settings object with the CurrentColor object correctly initialized. How can I apply the same ColorConverter JsonConverter to the Dictionary of Colors?

The same question applies to a recursive object tree:

[JsonObject(MemberSerialization.OptIn)]
public class DisplayPanel
{
    [JsonProperty] public List<DisplayPanel> Children;
}

where DisplayPanel requires its own JsonConverter.

The issue is not that each object is an (unknown) derived class of some base class; each Color / DisplayPanel object in the Dictionary / List has the exact same class.

  • 1
    Easiest way may be to make use of the `[JsonConstructor]` flag and write a constructor that takes the json data and construct the collection as you see fit. – Wobbles Apr 11 '16 at 12:00
  • Check out this answer: http://stackoverflow.com/questions/11754633/newtonsoft-json-serialize-and-deserialize-class-with-property-of-type-ienumerabl . I think the solution is there – Siderite Zackwehdex Apr 11 '16 at 12:01
  • 1
    Use [`[JsonProperty(ItemConverterType = typeof(ColorConverter))]`](http://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonPropertyAttribute_ItemConverterType.htm) as is shown in [Deserialize JSON dictionary values with JsonConverter](https://stackoverflow.com/questions/33674734/deserialize-json-dictionary-values-with-jsonconverter). It works for collection items also. – dbc Apr 11 '16 at 13:37
  • Thanks dbc, that's exactly it – Ronald In 't Velt Apr 11 '16 at 14:20

1 Answers1

-1

Write a method which iterates through each Color of ColorSet dictionary and calls JsonConvert.DeserializeObject() converter on each of them. Call this method when you are initializing the dictionary.

Guru HG
  • 112
  • 1
  • 2