我得到一个作为JSON字符串的HTTP响应。我正在将响应转换为JObject。响应包含";会话";节点,并且它包含更多会话值每个会话包含";事件";具有一个或多个";事件";每个事件包含";类型";以及";ArbitaryData";ArbitaryData包含";兴趣";。
我正试图把所有的";利息";值,但是如果事件类型="0";搜索";。
除了for循环之外,还有什么有效的方法可以做到这一点?
JObject json = JObject.Parse(guestJsonResponse);
var sessions = json.SelectToken("sessions");
var events = sessions.SelectTokens("events");
下面是我的JSON字符串响应示例
{
"firstName":"fn",
"lastName":"ln",
"gender":"male",
"sessions":[
{
"currency":"USD",
"events":[
{
"type":"SEARCH",
"status":"PROCESSED",
"arbitraryData":{
"interest":"Health"
}
},
{
"type":"CHECK",
"status":"PROCESSED",
"arbitraryData":{
"interest":"Dental"
}
}
]
},
{
"currency":"USD",
"events":[
{
"type":"SEARCH",
"status":"PROCESSED",
"arbitraryData":{
"interest":"Health"
}
},
{
"type":"CHECK",
"status":"PROCESSED",
"arbitraryData":{
"interest":"Dental"
}
}
]
},
{
"currency":"USD",
"events":[
{
"type":"SEARCH",
"status":"PROCESSED",
"arbitraryData":{
"interest":"Health"
}
},
{
"type":"CHECK",
"status":"PROCESSED",
"arbitraryData":{
"interest":"Dental"
}
}
]
}
]
}
此代码将返回所有"利息";值,其中事件类型="0";搜索";
List<string> interests = ((JArray)JObject.Parse(json)["sessions"])
.SelectMany(i => ((JArray)i["events"]))
.Where(x => (string)x["type"] == "SEARCH")
.Select(x => (string)x["arbitraryData"]["interest"])
.ToList();