【问题标题】:Multi-Object JSON, "Cannot deserialize the current JSON object"多对象 JSON,“无法反序列化当前 JSON 对象”
【发布时间】:2015-04-18 16:22:17
【问题描述】:

好吧,首先,答案可能很简单……但经过 45 分钟的尝试和谷歌搜索后,我还是想不通!


所以我在让这个 Json 正确解析时遇到了一些问题。我用http://json2csharp.com/ 创建了这些类,只是它没有告诉我解析它的代码。

我目前的课程:

public class Representations
{
    public string thumb { get; set; }
    public string large { get; set; }
    public string full { get; set; }
}

public class Search
{
    public string id { get; set; }
    public string file_name { get; set; }
    public Representations representations { get; set; }
}

public class SearchQuery
{
    public List<Search> search { get; set; }
    public int total { get; set; }
}

JSON:

    {
  "search": [
    {
      "id": "0300",
      "file_name": "0300.JPG",
      "representations": {
        "thumb": "thumb.jpg",
        "large": "large.jpg",
        "full": "0300.jpg"
      },
    },
    {
      "id": "0000",
      "file_name": "0000.JPG",
      "representations": {
        "thumb": "thumb.jpg",
        "large": "large.jpg",
        "full": "0000.jpg"
      },
    },
    {
      "id": "0d00",
      "file_name": "0d00.JPG",
      "representations": {
        "thumb": "thumb.jpg",
        "large": "large.jpg",
        "full": "0d00.jpg"
      },
    }
  ],
  "total": 3
}

和代码:

searchresults = JsonConvert.DeserializeObject<List<SearchQuery>>(JSONCode);

【问题讨论】:

    标签: c# json c#-4.0 json.net


    【解决方案1】:

    您应该反序列化为SearchQuery,而不是List&lt;SearchQuery&gt;

    SearchQuery result = JsonConvert.DeserializeObject<SearchQuery>(JSONCode);
    

    然后使用search 属性访问搜索结果列表:

    List<Search> searchResults = result.search;
    

    【讨论】:

    • 虽然 List searchResults 对我不起作用。但 Search searchResults 可以。
    • 这取决于您声明 searchResults 变量的类型。从您的代码中,这并不太清楚。在我的示例中,我已将 searchResults 变量分配给 List&lt;Search&gt;,但您可以随意使用任何您想要的命名和类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2021-12-03
    • 1970-01-01
    • 2017-03-06
    • 2017-10-28
    相关资源
    最近更新 更多