Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using newtonsoft, how to deserialize without knowing the type till run time?

Tags:

json

json.net

so the followwing works just fine, giving me a Team object from the string json:

var found = JsonConvert.DeserializeObject<Team>(json);

but what if I won't know the type until runtime? Say I've got the string json as above, but I also have another string with the type name? for example, this isn't working:

var found = JsonConvert.DeserializeObject(json, Type.GetType("Team"));

Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type ...

like image 871
Travis Laborde Avatar asked Oct 10 '12 01:10

Travis Laborde


People also ask

How does Newtonsoft JSON deserialize work?

Newtonsoft. Json uses reflection to get constructor parameters and then tries to find closest match by name of these constructor parameters to object's properties. It also checks type of property and parameters to match. If there is no match found, then default value will be passed to this parameterized constructor.

How do you deserialize an object type in C#?

NET objects (deserialize) A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is JsonConverter?

A converter is a class that converts an object or a value to and from JSON. The System. Text. Json namespace has built-in converters for most primitive types that map to JavaScript primitives.

Does JSON deserialization call constructor C#?

This is by design, when deserializing a JSON into a class, the constructor is not executed.


1 Answers

This worked for me:

var type = Type.GetType("My.Namespace.Class");
var myObj = JsonConvert.DeserializeObject(item, type);

The trick is to make sure that type is not null by providing the correct class name. If it is, the Deserialization can still work, but the output won't be the type you are wanting. See MSDN for more info on GetType.

like image 93
nick_w Avatar answered Sep 30 '22 18:09

nick_w