我有一个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; }
}
答案 0 :(得分:2)
你可以在这样的响应中包装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;