0

I have a json structured like that:

{
  "eventType1": {
    "unitName": "nameValue",
    "comment": "initial comment"
  },
  "eventType2": {
    "comment": "initial message"
  },
}

When I deserialize it the appropriate type seems to be something like Dictionary<string, <Dictionary<string,string>>> and method would look like that:

public static Dictionary<string, Dictionary<string, string>> defaultFieldDataByEvent =
        JsonConvert
        .DeserializeObject<Dictionary<string, Dictionary<string, string>>>(defaultFieldDataByEventSerialized);

which looks, well, ugly. But that's exactly how I need it to extract the data - defaultFieldDataByEvent[eventType][field].

Can I encapsulate the type into something somehow or is there a different approach to such cases?

ephemeris
  • 755
  • 9
  • 21
  • Is there a fixed set of possible properties for the `"eventTypeX"` objects? If so, I would define an `EventData` class and deserialize to `Dictionary` – dbc May 20 '18 at 16:38
  • @dbc, not exactly, that's why a dictionary, not a defined custom class. I would define an `EventData` class otherwise. I'd like to do it here as well, but I don't know how to populate the encapsulated dictionary when deserializing – ephemeris May 20 '18 at 16:44
  • 1
    If `EventData` would need to consist of fixed and variable properties, `[JsonExtensionData]` might fit your needs. See [How to serialize a Dictionary as part of its parent object using Json.Net](https://stackoverflow.com/q/14893614/3744182). – dbc May 20 '18 at 18:14
  • You may try to add a type alias with `using` directive to make code shorter, but this won't be convenient if logic is spread across multiple files. – Uladzislaŭ May 20 '18 at 18:27

1 Answers1

0

I see multiple possible options here. Hope any of these helps.

  • You may try to add a type alias with using directive to make code shorter, but this won't be convenient, if logic is spread across multiple files, because you will be forced to duplicate this alias.
  • You may try to use JObject.Parse for deserialization, staying on lower level. But as far as your json structure is pretty various, this approach may work well.
  • You may try to deserialize your data into ExpandoObject. It's rather similar to JObject, except you will get pretty nice dynamic code (dynamic is not a problem here since compiler won't help you with Dictionary either), but it, obviously will be less performant. You could lose your custom types information, since everything in your graph will become an ExpandoObject, but seems like that's not an issue for your case. Example may be found here.
  • You may try to use [JsonExtensionData] as @dbc suggested. See How to serialize a Dictionary as part of its parent object using Json.Net.
Uladzislaŭ
  • 1,680
  • 10
  • 13