我从服务器的响应中得到了以下json字符串,如下所示:
{
"resultCount": 2,
"results": [
{
"apartmentNo": "",
"city": "BEOGRAD",
"floor": "",
"houseNo": "99",
"houseNo2": "",
"phoneNo": "011\/000-0000",
"postalCode": "11000",
"region": "SOME REGION",
"street": "SOME STREET",
"firstName": "FNAME",
"lastName": "LNAME"
},
{
"apartmentNo": "",
"city": "BEOGRAD",
"floor": "",
"houseNo": "99",
"houseNo2": "",
"phoneNo": "011\/000-0000",
"postalCode": "11000",
"region": "SOME REGION",
"street": "SOME STREET",
"firstName": "FNAME",
"lastName": "LNAME"
}
]
}
可以看出,json响应中存在两个属于“result”的结果,它被分隔为{... first ...},{... second ...}。我已经知道如何只处理一个结果,但是如何处理两个或更多结果,比如这个json示例?
我想将此数据添加到数据网格视图以向用户显示结果。
我解析单个结果的代码是:
JObject o = JObject.Parse(responseText);
string ime = o["results"]["firstName"].ToString();
string prezime = o["results"]["lastName"].ToString();
string adresa = o["results"]["street"].ToString() + " " + o["results"]["houseNo"].ToString();
string mesto = o["results"]["city"].ToString();
string pbroj = o["results"]["postalCode"].ToString();
string tel = o["results"]["phoneNo"].ToString();
dataGridView1.Rows.Clear();
dataGridView1.Rows.Add(ime, prezime, adresa, mesto, pbroj, tel);
我还在这里找到了一种方法来识别所有使用jtokens的孩子但是必须有更好的方法来解析这些等多个数组,我使用的是Newtonsoft.Json。
非常感谢。
答案 0 :(得分:3)
您可以使用POO
/模型,如下所示
public class Result
{
public string apartmentNo { get; set; }
public string city { get; set; }
public string floor { get; set; }
public string houseNo { get; set; }
public string houseNo2 { get; set; }
public string phoneNo { get; set; }
public string postalCode { get; set; }
public string region { get; set; }
public string street { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
}
public class RootObject
{
public int resultCount { get; set; }
public List<Result> results { get; set; }
}
并像这样解析它
var root = JsonConvert.DeserializeObject<RootObject>("your json here ");