How to deserialize json array when i don't know what class i use?

Viewed 885

I have a json

var j = @"
    [{"Name":"John","Age":27},
     {"Name":"Mike","Age":30},
     {"Name":"Eric","Age":21}
    ]";

And class:

public class Worker
{
    public string Name{set;get;}
    public int Age{set;get;}
} 

And how i can deserialize it with Newtonsoft.Json:

List<Worker> videogames = JsonConvert.DeserializeObject<List<Worker>>(j);

But what if i don't know what class I want to deserialize and have just a type?

var worker = new Worker();
Type myType = worker.GetType();

How can i deserialize this json string in this case?

2 Answers

Just use the JsonConvert.DeserializeObject overload that accepts a Type, passing in a constructed list type:

Type listType = typeof(List<>).MakeGenericType(myType);
object list = JsonConvert.DeserializeObject(json, listType);

Of course you won't be able to use that in a statically-type-safe way afterwards - something is likely to need to cast it - but that's unavoidable if you're trying to use a type only known at execution time.

If you know that you are deserialising an object that is a list of a specific type, and you are aware of the name of the type you are using, then you can use generics to give you something strictly typed. For example:

public static List<T> DeserializeJsonList<T>(string json) 
{
   return JsonConvert.DeserializeObject<List<T>>(json);
}

And to use something like this, you could write:

string myJson = "[json goes here]";
List<MyType> myList = DeserializeJsonList<MyType>(string json);

However, if the type is anonymous (you only have a Type object instance, then you will likely have to resort to Jon Skeet's answer instead.

Related