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 ...
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.
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.
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.
This is by design, when deserializing a JSON into a class, the constructor is not executed.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With