所以我给了一个类似下面的json树,我真的只需要从这里得到人名和姓,但我在解析数据时遇到问题。
{
"results":[
{
"id":{
"key":"Phone.81dd6fef-a2e2-4b08-cfe3-bc7128b43786.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Phone.81dd6fef-a2e2-4b08-cfe3-bc7128b43786.Durable.json?api_key=",
"type":"Phone",
"uuid":"81dd6fef-a2e2-4b08-cfe3-bc7128b43786",
"durability":"Durable"
},
"line_type":"Landline",
"belongs_to":[
{
"id":{
"key":"Person.1ffee2ef-cc88-4a1e-87b0-05349571b801.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Person.1ffee2ef-cc88-4a1e-87b0-05349571b801.Durable.json?api_key=",
"type":"Person",
"uuid":"1ffee2ef-cc88-4a1e-87b0-05349571b801",
"durability":"Durable"
},
"type":"Full",
"names":[
{
"salutation":null,
"first_name":"fred",
"middle_name":null,
"last_name":"jones",
"suffix":null,
"valid_for":null
}
],
"age_range":null,
"gender":null,
"locations":[
{
"id":{
"key":"Location.bd4721f0-ba97-4ade-aac1-ed1f16be57ed.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Location.bd4721f0-ba97-4ade-aac1-ed1f16be57ed.Durable.json?api_key=",
"type":"Location",
"uuid":"bd4721f0-ba97-4ade-aac1-ed1f16be57ed",
"durability":"Durable"
},
"type":"Address",
"valid_for":{
"start":{
"year":2011,
"month":7,
"day":5
},
"stop":null
},
"legal_entities_at":null,
"city":"",
"postal_code":"",
"zip4":null,
"state_code":"",
"country_code":"",
"address":"",
"house":"10",
"street_name":"",
"street_type":"Ave",
"pre_dir":null,
"post_dir":null,
"apt_number":null,
"apt_type":null,
"box_number":null,
"is_receiving_mail":false,
"not_receiving_mail_reason":null,
"usage":null,
"delivery_point":null,
"box_type":null,
"address_type":null,
"lat_long":{
"latitude":,
"longitude",
"accuracy":"Street"
},
"is_deliverable":true,
"standard_address_line1":"",
"standard_address_line2":"",
"standard_address_location":"",
"is_historical":false,
"contact_type":"Home",
"contact_creation_date":1361177323
}
],
我到目前为止使用的代码是:
string url = String.Format("https://proapi.whitepages.com/2.1/phone.json?api_key={0}&phone_number={1}", WhitePagesConstants.ApiKey, number);
using (WebClient webClient = new System.Net.WebClient())
{
WebClient n = new WebClient();
n.Encoding = System.Text.Encoding.UTF8;
var json = n.DownloadString(url);
Dictionary<string, Object> formattedjson = JsonConvert.DeserializeObject<Dictionary<string, Object>>(json);
}
我已经这么久了,必须尽快完成它,所以我请求帮助我遍历这棵树。我之前从未与json合作过,而且我很失落如何做到这一点。我需要的确切信息是&#34; belongs_to&#34; - &GT; &#34;名称&#34; - &GT;第一和最后。我改变了一些名字以保护无辜者。
答案 0 :(得分:2)
如果您只需提取多个属性,则只需导航路径:
dynamic o = JsonConvert.DeserializeObject(json);
Console.WriteLine(o.results[0].belongs_to[0].names[0].first_name);
Console.WriteLine(o.results[0].belongs_to[0].names[0].last_name);
或者,如果您更喜欢字符串字典而不是动态对象:
JObject j = JsonConvert.DeserializeObject<JObject>(json);
Console.WriteLine(j["results"][0]["belongs_to"][0]["names"][0]["first_name"]);
Console.WriteLine(j["results"][0]["belongs_to"][0]["names"][0]["last_name"]);
P.S。你的JSON坏了。如果你提供了一个正确的例子,我会更容易测试代码。