[英]How to convert a JSON string using LINQ in C#
我正在嘗試從下面的 JSON 訪問一些鍵/值:
{
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#Collection(microsoft.graph.scheduleInformation)",
"value": [
{
"scheduleId": "xxxx@yyy.com",
"availabilityView": "0000000000200022",
"scheduleItems": [
{
"isPrivate": false,
"status": "busy",
"subject": "test",
"location": "Réunion Microsoft Teams",
"start": {
"dateTime": "2020-01-29T15:00:00.0000000",
"timeZone": "Romance Standard Time"
},
"end": {
"dateTime": "2020-01-29T15:30:00.0000000",
"timeZone": "Romance Standard Time"
}
},
{
"isPrivate": false,
"status": "busy",
"subject": "HG ",
"location": "fgfg",
"start": {
"dateTime": "2020-01-29T17:00:00.0000000",
"timeZone": "Romance Standard Time"
},
"end": {
"dateTime": "2020-01-29T18:00:00.0000000",
"timeZone": "Romance Standard Time"
}
}
]
}
]
}
我想為“開始”和“結束”子項檢索“日期時間”。 為此,我在 WPF 程序中使用了很少的 LINQ 代碼:
JObjeretrict gS = JObject.Parse(JSON);
var result = from s in gS["value"]["scheduleItems"]
orderby s["start"]["dateTime"]
select new
{
startTime = (DateTime)s["start"]["dateTime"],
endTime = (DateTime)s["end"]["dateTime"]
};
但它失敗並出現以下錯誤:
System.ArgumentException: Accessed JArray values with invalid key value: "scheduleItems". Int32 array index expected.
我已經使用以下 LINQ to JSON 完成了另一個 JSON 文件:
var rFMT = from m in fMT["meetingTimeSuggestions"]
orderby m["meetingTimeSlot"]["start"]["dateTime"]
select (DateTime)m["meetingTimeSlot"]["start"]["dateTime"];
以上,只對“開始”“日期時間”感興趣。 沒關系!
幫助!
首先,為什么 JSON 字符串有一個數組,其中value
鍵只有一個元素? 您可以刪除value
鍵的括號[]
,您的代碼應該可以工作。
如果您使用的是靜態類型語言,我認為最好創建嵌套類並使用它們反序列化 JSON 字符串。 但是作為代碼的替代方案,如果您想使用一次並忽略性能問題,這樣的代碼應該適合您:
// JSON: your json string value
var result = (JsonConvert.DeserializeObject<dynamic>(JSON)
.value[0].scheduleItems as IEnumerable<dynamic>)
.Select(x => new {
start = (DateTime)x.start.dateTime,
end = (DateTime)x.end.dateTime
});
我想我已經找到了哪里出錯了。
"value":[...]
是一個數組,因此您可以訪問所有數組項(在這種情況下只有一個),或者在您的查詢中指定值項在這種情況下將是["value"][0]
我不確定 value 是否需要是一個數組。 盡管如此,這現在有效:
var result = from s in gS["value"][0]["scheduleItems"]
orderby s["start"]["dateTime"]
select new
{
startTime = (DateTime)s["start"]["dateTime"],
endTime = (DateTime)s["end"]["dateTime"]
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.