1

Here is a response from the API:

{"success":true,"data":[{"_id":"559276d1f21a16dc28f8cd67","name":"Businessman","__v":0}]}

All of the server methods return a Json object in the format:

{ "success": "true/false", data: "object_array[]" }

or:

{ "success": "true/false", data: "single_object" }

So I should have a C# object for the response and also I need to have different object types for the "data" part of the response. The "data" property will be arrays of different types or sometimes a single object.

Is there a dynamic way to handle this scenario or should I define different types for each of the responses?

Thanks.

Élodie Petit
  • 5,774
  • 6
  • 50
  • 88
  • That depends on what you want. You could just deserialize to a dynamic object, but then you won't get any design time property checking or intellisense. I personally would create objects for each. – pquest Aug 03 '15 at 14:18

1 Answers1

1

You can use dynamic keyword.

dynamic jObj = JObject.Parse(json);
Console.WriteLine(jObj.success);

if(jObj.data is JArray)
{
    Console.WriteLine(jObj.data[0].name);
}

if (jObj.data is JObject)
{
    Console.WriteLine(jObj.data.name);
}
EZI
  • 15,209
  • 2
  • 27
  • 33