Value can be a string or an object

Dec 3, 2009 at 3:45 PM

I'm having trouble thinking about exactly how I can create my C# object to work with this JSON.  I have a class like this:

 

public class MyResponse
{
 public string Result {get;set;}
 public string Response {get;set;}
}

This works great for my JOSN: {"Result":"Value","Response":"Value"}

Now I have to modify this so that it can handle this JSON as well.

{"Result":"Value","Response":{"key1":"value1","key2":"value2"}}

Sometimes Response will be a single string - sometimes it will be another JSON object.

How would you think about starting to go about solving this problem?  I first thought about having ResponseString and ResponseDictionary properties and somehow making only one of them be put into the Response's value.  Any ideas?  Thanks.

 

Coordinator
Dec 6, 2009 at 10:22 PM

If you make the Response property an object instead of a string then its value should be deserialized as a JToken. It will be a JValue if the value is a string and a JArray if the value is an array. You can then convert from either to a string or collection of strings quite easily.