Destroy JSON object to .Net object with NewtonSoft

I have a json Object that I want to deserialize into my .Net type without dropping it.

I think I read somewhere in the document that you can pass the attribute to json to tell the deserializer the type of .Net object that it can try to execute.

I can not find where I read this.

I want to avoid using

var myNewObject = JsonConvert.DeserializeObject<MyClass>(json);

To get something like this

MyClass myNewObject = JsonConvert.DeserializeObject(json);

I got my json object from HttpRequest and want to instantiate the corresponding class from this nested object. Currently, deserializing into a known subject works well, but something more flexible is required, without having to manage the entire known object from the parsing method.

+4
3

json, .

,

public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
   TypeNameHandling = TypeNameHandling.Objects
};

:

var json = JsonConvert.SerializeObject(data, Settings);

json:

{
   "$type":"YourNamespaceOfTheClass",
   "YourPropertyInTheClass":valueOfProperty
}

:

var object = JsonConvert.DeserializeObject(json, Settings);

json , . json .

+6

:

dynamic myNewObject = JsonConvert.DeserializeObject(json);

, .

Console.WriteLine(myNewObject.data[0].description);

, , JSON data, description.

+2

- :

var result = JsonConvert.DeserializeObject<dynamic>(json);

. Cast , anynymous , . !

0
source

Source: https://habr.com/ru/post/1620075/


All Articles