Deserialize single object or array of objects

May 13, 2009 at 6:36 PM

Hi, I have a scenario where I need to deserialize json string, that can represent either a single object of a certain type or an array of objects of this type, and I don't know ahead of time what exactly it is going to be. If I knew that I wouldn't have a problem.

Right now the following line throws an exception if json represents an array of MyClass objects
MyClass result = JsonConvert.DeserializeObject<MyClass>(json);

And this line returns empty List if json represents a single object
List<MyClass> result = JsonConvert.DeserializeObject<List<MyClass>>(json);

How can I solve this problem?

Thanks in advance.

Coordinator
May 15, 2009 at 9:42 AM

You could create a JsonTextReader, call Read and then take a look at the first token to see whether it is a StartObject or StartArray.

May 15, 2009 at 1:24 PM

Great, thanks a lot. BTW, excellent library!!! Keep it up.