3

Having json strings like this (I have no control over the publisher):

{
  "TypeName": "Type1"
}

{
  "TypeName": "Type1"
}

Is this an acceptable way to deserialize the json strings dynamically?:

public class DeserializationFactory
{
    public static IPoco GetEvent(string jsonString)
    {
        var o = JObject.Parse(jsonString);
        IPoco poco = null;
        switch (o["TypeName"].ToString())
        {
        case "Type1":
            poco = JsonConvert.DeserializeObject<Type1>(jsonString);
            break;

        case "Type2":
            poco = JsonConvert.DeserializeObject<Type2>(jsonString);
            break;
        }
        return poco;
    }
}
cs0815
  • 13,862
  • 32
  • 107
  • 253
  • Are you saying you aren't sure which Poco you should deserialize to? – Greg Feb 03 '16 at 16:53
  • Not really. It depends on the value of "TypeName" – cs0815 Feb 03 '16 at 17:22
  • You might want to do it with a `JsonConverter` in case your `IPoco` gets included in some higher level object. See http://stackoverflow.com/questions/19307752/deserializing-polymorphic-json-classes-without-type-information-using-json-net or http://stackoverflow.com/questions/29528648/json-net-serialization-of-type-with-polymorphic-child-object – dbc Feb 03 '16 at 17:42

1 Answers1

2

You can try with JsonSubtypes converter implementation and this layout:

    [JsonConverter(typeof(JsonSubtypes), "TypeName")]
    [JsonSubtypes.KnownSubType(typeof(Type1), "Type1")]
    [JsonSubtypes.KnownSubType(typeof(Type2), "Type2")]
    public interface IPoco
    {
        string TypeName { get; }
    }

    public class Type1 : IPoco
    {
        public string TypeName { get; } = "Type1";
        /* ... */
    }

    public class Type2 : IPoco
    {
        public string TypeName { get; } = "Type2";
        /* ... */
    }
manuc66
  • 1,777
  • 20
  • 21