1

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: ...
}
dbc
  • 104,963
  • 20
  • 228
  • 340
90abyss
  • 7,037
  • 19
  • 63
  • 94
  • 1
    Do you also control the serializing side? If so, you could create a wrapper class for all 3 types and serialize that. – Thoryn Hawley Jan 26 '18 at 23:57
  • A quick (if slightly dirty) way to do it is to search the JSON string for the typename. – Thoryn Hawley Jan 26 '18 at 23:58
  • 1
    `JavaScriptSerializer` is not currently recommended for new development by Microsoft (they recommend [tag:json.net] instead) but it does support polymorphic type hinting. See [JavaScriptSerializer with custom Type](https://stackoverflow.com/q/1027107/3744182). – dbc Jan 27 '18 at 01:06

2 Answers2

1

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".

Matthew Groves
  • 25,181
  • 9
  • 71
  • 121
0

I recommend to use JSON.NET instead of JavaScriptSerializer.

If ParseJSON return object with types of Question, Answer and ... you can use workaround below:

var jsonType = ParseJson(payload);
switch (jsonType.GetType().FullName)
{
   case "YourAssembly.Question": {Question question = new JavaScriptSerializer().Deserialize<Question>(payload); break;}
   case "YourAssembly.Answer": ...
   case "YourAssembly.Comment": ...
}
Ali Bahrami
  • 5,935
  • 3
  • 34
  • 53