【问题标题】:Deserializing JSON object to array or list将 JSON 对象反序列化为数组或列表
【发布时间】:2017-09-28 12:25:49
【问题描述】:

我仍然不完全确定要问什么,所以如果这是错误的构想,我深表歉意。我发现的其他问题与已经在 J​​SON 中接收对象数组的人有关。

我的 JSON 字符串作为对象从第三方返回,而我之前只处理过它作为数组返回,过去很容易转换为对象。

var success = JsonConvert.DeserializeObject<RootObjectClass>(result); gives me a `Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`

我应该把它转换成一个数组吗?如果是的话,应该怎么做,因为这些对象是单独命名的,与属性“contact_id”的值相同?

否则,有人可以为我指出如何从这个 JSON 中获取联系人列表的最佳实践的正确方向。

JSON 结构如下所示。

{
    "status": true,
    "error_code": "",
    "error_message": "",
    "data": {
        "693": { // Contact obj, always the same as contact_id
            "contact_id": "693",
            // removed lots of properties for brevity
            "real_name": "Mike Hunt",
            "telephone": "01280845867",
            "email": "mhunt@test.com"
        },
        "767": { 
            "contact_id": "767",
            "real_name": "Peter File",
            "telephone": "02580845866",
            "email": "pfile@test.com"
        }
    }
}

类结构

[Serializable()]
[DataContract]
public class RootObjectClass
{
    [DataMember()]
    public bool status { get; set; }
    [DataMember()]
    public string error_code { get; set; }
    [DataMember()]
    public string error_message { get; set; }
    [DataMember()]
    public DataClass data { get; set; }
}
[Serializable()]
[DataContract]
public class DataClass
{
    [DataMember]
    public Contact contact { get; set; }
}

【问题讨论】:

  • 反序列化为dynamic 数据类型。然后你可以很容易地访问它的属性
  • 好的,谢谢,去看看
  • 你不需要RootObjectClass 中的DataClass 数组吗?
  • 除非(内部)类型与 JSON(内容和关系)非常匹配,否则我更喜欢使用 JSON to LINQ from Json.NET 拆分 JSON。
  • 不,你是对的,这应该读作 Data 类中的联系人数组,不知道为什么被砍掉了。

标签: c# arrays json deserialization


【解决方案1】:

您可以将data 属性反序列化为dictionary

[Serializable()]
[DataContract]
public class RootObjectClass
{
    [DataMember()]
    public bool status { get; set; }
    [DataMember()]
    public string error_code { get; set; }
    [DataMember()]
    public string error_message { get; set; }
    [DataMember()]
    public Dictionary<string,Contact> data { get; set; }
}

然后你可以像这样选择联系人:

var contacts = rootObject.data.Values.ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    相关资源
    最近更新 更多