Deserialize json with json.net c #

I am new to Json, so a bit green.

I have a rest-based service that returns a json string;

{"treeNode":[{"id":"U-2905","pid":"R","userId":"2905"}, {"id":"U-2905","pid":"R","userId":"2905"}]} 

I played with Json.net and am trying to deserialize a string into Object, etc. I wrote an extension method to help.

 public static T DeserializeFromJSON<T>(this Stream jsonStream, Type objectType) { T result; using (StreamReader reader = new StreamReader(jsonStream)) { JsonSerializer serializer = new JsonSerializer(); try { result = (T)serializer.Deserialize(reader, objectType); } catch (Exception e) { throw; } } return result; } 

I was expecting an array of treeNode [] objects. But it seems that I can only deserialize correctly if the treeNode [] property of another object.

 public class treeNode { public string id { get; set; } public string pid { get; set; } public string userId { get; set; } } 

Do I have a way to just get a direct array from deserialization?

Greetings

+5
source share
2 answers

You can use an anonymous class:

 T DeserializeJson<T>(string s, T templateObj) { return JsonConvert.Deserialize<T>(s); } 

and then in your code:

 return DeserializeJson(jsonString, new { treeNode = new MyObject[0] }).treeNode; 
+3
source

Unfortunately, JSON does not support type information, but serializes its pure dictionary of objects, not the full class data. You will need to write some kind of extension to extend the behavior of the JSON serializer and deserializer to support the correct type of marshalling.

Providing the root type displays the graph of objects correctly if the expected types are exact and non-derived types.

For example, if I have a property as an array of a base class, and my real value may contain derived child classes of any type. JSON does not fully support it, but the web service (SOAP) allows you to serialize objects with dynamic typing.

0
source

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


All Articles