简体   繁体   中英

Deserialize json with json.net c#

am new to Json so a little 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 have been playing with the Json.net and trying to Deserialize the string into Objects etc. I wrote an extention 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 its seems that I can only deserialize correctly if treeNode[] property of another object.

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

I there a way to to just get an straight array from the deserialization ?

Cheers

You could 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;

Unfortunately JSON does not support Type Information while serializing, its pure Object Dictionary rather then full Class Data. You will have to write some sort of extension to extend behaviour of JSON serializer and deserializer in order to support proper type marshelling.

Giving root type will map the object graph correctly if the types expected are exact and not derived types.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM