【问题标题】:Deserialize a json container array反序列化一个 json 容器数组
【发布时间】:2017-01-03 02:45:21
【问题描述】:

我试图反序列化的数据与这篇文章中的这个 json 完全一样>

Deserialize JSON Facebook feed using Gson,只有更多的对象,在容器内..我没有使用“Gson”

我认为有些对象甚至有自己的容器嵌套在某个地方,但这不是目前的问题,主要问题是我在反序列化到以下类时遇到问题..

public class Rootobject
{
    public int found { get; set; }
    public Post[] posts { get; set; }
    public Meta meta { get; set; }
}

我了解 API 中 json 的布局方式,它是某种数组,在 Json.net 文档中,他们称其为 DataSet。我正在使用 Json.Net

我最近的反序列化尝试是;

List<Rootobject> data = JsonConvert.DeserializeObject<List<Rootobject>>(stringData);

但数据仍然为空,我得到了;

补充资料:

无法反序列化当前 JSON 对象(例如 {"name":"value"}) 输入类型 'System.Collections.Generic.List`1[WebApplication17.Models.Rootobject]' 因为该类型需要一个 JSON 数组(例如 [1,2,3])来反序列化 正确。

也许 LINQ to JSON 是目前还不确定的方法.. 有什么建议吗?

【问题讨论】:

    标签: c# arrays json.net containers json-deserialization


    【解决方案1】:

    首先,帖子中的 JSON 不是有效的 JSON 字符串,因此无法反序列化。其次,我尝试纠正和纠正 JSON 以使其成为有效的 JSON,因此您的 JSON 看起来像

    {
        "data": [
            {
                "id": "105458566194298_411506355589516",
                "message": "...",
                "type": "status",
                "created_time": "2012-11-25T17:26:41+0000",
                "updated_time": "2012-11-25T17:26:41+0000",
                "comments": {
                    "count": 0
                }
            },
            {
                "id": "105458566194298_411506355589516",
                "message": "...",
                "type": "status",
                "created_time": "2012-11-25T17:26:41+0000",
                "updated_time": "2012-11-25T17:26:41+0000",
                "comments": {
                    "count": 0
                }
            }
        ]
    }
    

    所以类结构应该是这样的

    public class Comments
    {
        public int count { get; set; }
    }
    public class Datum
    {
        public string id { get; set; }
        public string message { get; set; }
        public string type { get; set; }
        public DateTime created_time { get; set; }
        public DateTime updated_time { get; set; }
        public Comments comments { get; set; }
    }
    public class MyData
    {
        public List<Datum> data { get; set; }
    }
    

    然后像你之前做的那样正常地解开它

    MyData data = JsonConvert.DeserializeObject<MyData>(stringData);
    

    【讨论】:

    • 有道理..您通过修改反模式 Json 所做的事情。我的代码更像这样,差异被“找到”。 { "found": 12, "posts": [ {}, {} ] } public class Rootobject { public int found { get;放; } 公共帖子 [] 帖子 { 获取;放; } 公共列表 数据 { 获取;放; } 公共元元 { 获取;放; } } 根对象数据 = JsonConvert.DeserializeObject(stringData);我无法更改来自 Wordpress 公共 API 的 Json ......无论如何,我接受了你的建议,我很确定它已经完成了如此出色的工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    相关资源
    最近更新 更多