Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON Object to .Net object with NewtonSoft

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.

like image 756
Leze Avatar asked Feb 08 '23 07:02

Leze


1 Answers

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.

like image 86
croxy Avatar answered Feb 12 '23 10:02

croxy