【问题标题】:Deserialize with Json.NET使用 Json.NET 反序列化
【发布时间】:2013-01-18 01:49:44
【问题描述】:

我正在搜索有关如何使用 Json.NET 反序列化对象的教程,但我找不到与我的类似的教程。

我有一个这样的 Json:

{
    "__ar":1,
    "payload":{
        "entries":[
        {
        "uid":100000011980844,
        "photo":"",
        "type":"user",
        "text":"testing",
        "path":"testing",
        "category":"",
        "needs_update":true,
        "non_title_tokens":"",
        "names":[
        "Test"
        ],
        "subtext":"",
        "score":0
        }
    ]
    }
}

然后,我尝试像这样反序列化:

var j = JsonConvert.DeserializeObject<People> (json);

然后:

public class People
{
    public string __ar { get; set; }
    public Payload payload { get; set; }
}

public class Payload
{
    public Person entries { get; set; }
}

public class Person
{
    public string uid { get; set; }
    public string photo { get; set; }
    public string type { get; set; }
    public string text { get; set; }
    public string path { get; set; }
    public string category { get; set; }
    public string needs_update { get; set; }
    public string non_title_tokens { get; set; }
    public string subtext { get; set; }
    public string score { get; set; }
    public List<string> names { get; set; }
}

但它没有工作,有谁知道我必须做些什么来修复它?错误信息是:

无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'QueryFacebook.Parser+Person' 因为该类型需要 JSON 对象 (例如 {"name":"value"})正确反序列化。修复此错误 将 JSON 更改为 JSON 对象(例如 {"name":"value"})或 将反序列化类型更改为数组或实现 集合接口(例如 ICollection、IList),例如 List 可以 从 JSON 数组反序列化。

【问题讨论】:

  • JsonArrayAttribute 也可以添加到类型以强制它从 JSON 数组反序列化。路径“payload.entries”,第 1 行,位置 32。

标签: c# json.net


【解决方案1】:

只需将Payload 的定义更改为如下所示即可

public class Payload
{
    public Person[] entries { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 2012-04-09
    • 1970-01-01
    • 2015-11-22
    • 2017-01-15
    • 1970-01-01
    相关资源
    最近更新 更多