Search code examples
c#asp.netjsonjavascriptserializer

How to switch on deserialized json's class type?


I'm getting a json which on deserializing could be of any class say:

  1. Question

  2. Answer

  3. Comment

So I need to switch based on what class that json belongs to.

Currently I'm using this to deserialize. But the problem is if I use this, I'm premeditating what type I'll receive.

Question question = new JavaScriptSerializer().Deserialize<Question>(payload);

But I want to do this instead:

var jsonType = ParseJson(payload);
switch (jsonType)
{
   case Question: {Question question = new JavaScriptSerializer().Deserialize<Question>(payload); break;}
   case Answer: ...
   case Comment: ...
}

Solution

  • This could be really tricky. If there is a "type" field that contains a value of "Question","Answer", or "Comment", you could switch on that. If not, you'll have to switch on something else and use it as an implicit marker. That can be dangerous if/when something changes.

    Anyway, you might try Newtonsoft JSON.NET, specifically JObject's TryGetValue (I don't know if there's an equivalent in Microsoft's JavaScriptSerializer):

        var jsonString = "{ \"foo\" : \"bar\" }";
        var obj = JObject.Parse(jsonString);
    
        if(obj.TryGetValue("foo", out JToken val1))
        {
            Console.Write("Foo is in there!");
        }
    

    In that example, val1 contains a value of "bar".