【发布时间】:2016-05-06 15:08:33
【问题描述】:
如何在 C# 中使用 JSON.NET 查询(查看属性是否存在)和枚举(数组属性)在复杂 JSON 对象中找到?
我从 API 接收到一个复杂的 JSON 对象,该对象具有可变数量/类型的属性。
我一直在阅读the JSON.Net Documentation,查看示例等,但没有走多远,迷失在 JObject、JArray、JToken、使用动态等...
我想找到pageResponses.scriptOutput 属性,验证它包含.items[] 数组,然后枚举/迭代数组。
编辑
我取得了进展,并在 JSON 数据示例中发现了拼写错误。
但是如何使用键名查询/枚举子对象,例如(item.location, item.timestamp)?
string json = File.ReadAllText(@"Output.json");
JObject jObj = JObject.Parse(json);
IList<JToken> items = jObj["pageResponses"][0]["scriptOutput"]["items"].ToList();
foreach (JToken item in items){
Console.WriteLine(item["location"]);
}
/*** Console Output ***/
// Austin, TX
// Anaheim, CA
// Adams, MN
// Barstow, CA
var varItems = from o in jObj["pageResponses"][0]["scriptOutput"]["items"].ToList() select o;
foreach (var item in varItems){
Console.WriteLine(item["timestamp"]);
}
/*** Console Output ***/
// 2016 - 05 - 03 19:53
// 2016 - 05 - 04 04:10
// 2016 - 05 - 04 08:18
// 2016 - 05 - 01 12:26
(为简洁起见,以下 JSON 示例被删减)
{
"meta": {
"outputAsJson": true,
"backend": {
"os": "linux",
"id": "10.240.0.3_2",
"requestsProcessed": 8
}
},
"pageResponses": [
{
"pageRequest": {
"renderType": "script",
"outputAsJson": true
},
"frameData": {
"name": "",
"childCount": 1
},
"events": [
{
"key": "navigationRequested",
"time": "2016-05-06T13:43:30.344Z"
},
{
"key": "navigationRequested",
"time": "2016-05-06T13:43:31.131Z"
}
],
"scriptOutput": {
"items": [
{
"location": "Austin, TX",
"timestamp": "2016-05-03 19:53",
"title": "User Login"
},
{
"location": "Anaheim, CA",
"timestamp": "2016-05-04 04:10",
"title": "User Logout"
},
{
"location": "Adams, MN",
"timestamp": "2016-05-04 08:18",
"title": "User Login"
},
{
"location": "Barstow, CA",
"timestamp": "2016-05-01 12:26",
"title": "User Logout"
}
]
},
"statusCode": 200
}
],
"statusCode": 200,
"content": {
"name": "content.json",
"encoding": "utf8"
},
"originalRequest": {
"pages": [
{
"renderType": "script",
"outputAsJson": true
}
]
}
}
【问题讨论】:
-
您可以创建一个类层次结构,对于您不想反序列化的任何属性,您可以使用
dynamic。如果要遍历层次结构,则需要使用递归函数。 -
另一个重要说明,如果您正在验证 JSON,那么您可以针对您创建的方案使用 JSON.Net 验证器。看here
-
看看这个documentation中的
parse方法 -
我会认真查看 json 架构,因为这听起来正是您所要求的:
I want to find the pageResponses.scriptOutput property, verify it contains
标签: c# json linq json.net linq-to-json