I got a json Object that i want to deserialize to its .Net type without casting it.
I think i read somewhere in the doc that you can pass an attribute into the json to tells to the deserializer the .Net object type that it can try to cast.
I can't find the where i read this.
I want to avoid use of
var myNewObject = JsonConvert.DeserializeObject<MyClass>(json);
To get something like this
MyClass myNewObject = JsonConvert.DeserializeObject(json);
I got my json object from an HttpRequest and want to instantiate the appropriate class from this nested object. Currently deserialization into an known item work good but need something more flexible without the need to manage all known Object from a parsing method.
You can save the object type in your json string like this.
The settings you have to hand over the converter
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
};
How to serialize with the given settings:
var json = JsonConvert.SerializeObject(data, Settings);
This is what your json string looks like:
{
"$type":"YourNamespaceOfTheClass",
"YourPropertyInTheClass":valueOfProperty
}
How to deserialize with the given settings:
var object = JsonConvert.DeserializeObject(json, Settings);
Now your json string contains not only the serialized object, but also the type of your serialized object. So you don't have to worry about the right type when deserializing your json string.
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