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;
    }
}
3
  • Are you saying you aren't sure which Poco you should deserialize to? Commented Feb 3, 2016 at 16:53
  • Not really. It depends on the value of "TypeName" Commented Feb 3, 2016 at 17:22
  • You might want to do it with a JsonConverter in case your IPoco gets included in some higher level object. See stackoverflow.com/questions/19307752/… or stackoverflow.com/questions/29528648/… Commented Feb 3, 2016 at 17:42

1 Answer 1

3

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";
        /* ... */
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.