我正在使用 json.net (Newtonsoft) 库来解析 API json 响应。我只需要 id 值和 rank 值。json 看起来像这样:
{"items":
[
{"fields":
{"entry":
[
{"key":"Customer","value":"ABC Electronics"},
{"key":"Status","value":"Untouched"},
{"key":"Amount","value":"$1000"},
{"key":"rank","value":"3.0"}
]
},
"id":"1001",
"owner":"dave@sales123.com"
},
{"fields":
{"entry":
[
{"key":"Customer","value":"General Products"},
{"key":"Status","value":"Developing"},
{"key":"Amount","value":"$6000"},
{"key":"rank","value":"6.0"}
]
},
"id":"1002",
"owner":"john@sales123.com"
}
]
}
我的类中有一个方法,它发出请求,遍历 json 并获取 id 和 rank,然后将这些值作为新的 RankScore 对象添加到 List 类成员。我的问题是,是否有更好的方法来找到条目数组中键 ==“排名”的“值”,而不仅仅是循环遍历它并检查每个键。我找不到任何 LINQ 方式?
public void MakeRequest(apiURL) {
var requestUrl = new Uri(apiUrl, "/ranks/0");
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
request.Credentials = new NetworkCredential(this.Username, this.Password);
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var token = JObject.Parse(reader.ReadToEnd());
var items = token["items"];
foreach (var item in items)
{
var id = item.Value<string>("id");
var entries = item["fields"]["entry"];
string rank = null;
// **** Is there a better way to do this? ****
foreach (var entry in entries)
{
if (entry.Value<string>("key") == "rank")
{
rank = entry.Value<string>("value");
break;
}
}
var ranking = new RankScore(int.Parse(id), rank);
this.Ranks.Add(ranking);
}
}
}
}