Deserialize json with json.net c#

…衆ロ難τιáo~ 提交于 2020-01-01 05:36:07

问题


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


回答1:


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;



回答2:


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.



来源:https://stackoverflow.com/questions/1378335/deserialize-json-with-json-net-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!