反序列化JSON与json.net C# [英] Deserialize json with json.net c#

查看:101
本文介绍了反序列化JSON与json.net C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是新来的Json那么一点点绿色

am new to Json so a little green.

我有一个基于REST的服务,它返回一个JSON字符串;

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"}]}

我一直在玩的Json.net并试图反序列化串入对象等
我写了一个延伸的方法来帮助。

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;
        }



我期待treeNode的[]对象的数组。但它似乎我只能正确地反序列化,如果treeNode的[]另一个对象的属性。

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 ?

干杯

推荐答案

您可以使用一个匿名类:

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;

这篇关于反序列化JSON与json.net C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆