【问题标题】:Bind DropDownList from JSON从 JSON 绑定 DropDownList
【发布时间】:2017-05-18 18:21:28
【问题描述】:

在以下 JSON 响应方面需要帮助。我尝试反序列化

JSON 响应

{  
"entities":[  
    {  
        "id":"/Severity/Critical",
        "Name":"Critical"
    },
    {  
        "id":"/Severity/High",
        "Name":"High"
    },
    {  
        "id":"/Severity/Low",
        "Name":"Low"
    },
    {  
        "id":"/Severity/Normal",
        "Name":"Normal"
    }
],
"paging":{  
    "from":4,
    "limit":100,
    "hasMore":false
}
}

var severity = JsonConvert.DeserializeObject<Severity>(json);

错误信息

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以从 JSON 数组反序列化的列表。也可以将 JsonArrayAttribute 添加到类型中以强制它从 JSON 数组中反序列化。

【问题讨论】:

  • 您应该考虑格式化您的帖子以使其更易于阅读。

标签: c# json serialization


【解决方案1】:

正如 ErrorMessage 告诉您的那样,JsonConvert.DeserializeObject 无法将您用作输入的 JSON 转换为对象。为避免这种情况,您可以声明一个特定的类,在该类中您的 JSON 将被反序列化。接受您共享的输入,这个类可能如下所示:

public class Severity
{

    [JsonProperty("entities")]
    public List<Entity> Entities { get; set; }

    [JsonProperty("paging")]
    public Paging Paging { get; set; }
}

public class Entity
{
    [JsonProperty("id")]
    public string Id;

    [JsonProperty("Name")]
    public string Name;
}

public class Paging
{
    [JsonProperty("from")]
    public int From { get; set; }

    [JsonProperty("limit")]
    public int Limit { get; set; } 

    [JsonProperty("hasMore")]
    public bool HasMore { get; set; } 
}

那么你可以这样做:

var severity = JsonConvert.DeserializeObject<Severity>(json);

【讨论】:

  • 这太完美了。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多