Deserialize json with json.net c#

Posted by 76mel on Stack Overflow See other posts from Stack Overflow or by 76mel
Published on 2009-09-04T10:06:02Z Indexed on 2011/01/17 2:53 UTC
Read the original article Hit count: 257

Filed under:
|

Hi, 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

© Stack Overflow or respective owner

Related posts about c#

Related posts about json.net