从JSON响应序列化JSON对象数组
本文关键字:JSON 数组 对象 响应 序列化 | 更新日期: 2023-09-27 18:18:57
我有一个json响应看起来像这样:
"corps":
[
{
"id": "1007",
"company_id": "1007",
"org_name": "My organization 1",
"org_addr1": "123 W. 1234 S.",
"org_addr2": "",
},
{
"id": "1008",
"org_name": "My organization 2",
"org_addr1": "123 W. 1234 S.",
"org_addr2": "",
}
]
我已经成功地获得了一个响应到我的HCO对象正确使用:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HCO));
HCO Company = (HCO)serializer.ReadObject(response.Content.ReadAsStreamAsync().Result);
这很好,但我正试图让所有元素在军团。所以我想试试这样做:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HCO));
HCO element = (HCO)serializer.ReadObject(response.Content.ReadAsStreamAsync().Result);
Companies.Add(element);
但这根本行不通。我如何解析json结果,然后序列化响应中的每个元素?
HCO类:
public class HCO
{
public int id { get; set; }
public int comapny_id { get; set; }
public string org_name { get; set; }
public string org_addr1 { get; set; }
public string org_addr2 { get; set; }
}
您可以像这样将HCO类封装在响应中:
public class HCOResponse
{
public List<HCO> corps {get; set;}
}
然后使用DataContractJsonSerializer对json进行反序列化,如下所示:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HCOResponse));
Companies = (HCOResponse)serializer.ReadObject(response.Content.ReadAsStreamAsync().Result);
希望有帮助。
编辑:(来自反馈)
HCOResponse hco_resp = (HCOResponse)serializer.ReadObject(response.Content.ReadAsStreamAsync().Result);
Companies = hco_resp.corps;