我有一個JSON文件,我希望獲得屬性值land_use_type
內部的數組屬性records
。我的第一次嘗試是使用LINQ到JSON與Newtonsoft參考,但始終LINQ給我這個消息:C#linq to json如何讀取數組中的屬性值
System.Collections.Generic.List'1 [Newtonsoft.Json.Linq.JToken]
C#代碼:
string path = @"C:\...\json1.json";
using (StreamReader read = File.OpenText(path))
{
JObject jsondata = (JObject)JToken.ReadFrom(new JsonTextReader(read));
string bearing = (string)jsondata["bearing"];
string distance = (string)jsondata["distance"];
string source = (string)jsondata["source"];
var Land_use = from x in jsondata["records"]
select x["land_use_type"];
Console.WriteLine(String.Format("{0}\n{1}\n{2}\n{3}", bearing, distance, source, Land_use.ToList()));
JSON文件:
{
...
"records": [
{
"crop_primary": 0,
"crop_primary_coverage": null,
"crop_secondary": 0,
"crop_secondary_coverage": null,
"crop_tertiary": 0,
"crop_tertiary_coverage": null,
"date_created": "2017-02-27T20:25:28.981681",
"date_updated": "2017-02-27T20:25:28.981681",
"history": [
{
"data": "{\"crop_primary\": 0, \"crop_primary_coverage\": null, \"crop_secondary\": 0, \"crop_secondary_coverage\": null, \"crop_tertiary\": 0, \"crop_tertiary_coverage\": null, \"date_created\": \"2017-02-27T20:25:28.981681\", \"date_updated\": \"2017-02-27T20:25:28.981681\", \"id\": 172812, \"intensity\": 0, \"land_use_type\": 3, \"location_id\": 272769, \"month\": 2, \"ndvi\": null, \"ndvi_mean\": null, \"protected\": false, \"rating\": 0, \"scale\": -1, \"source_class\": null, \"source_description\": \"mobile_application\", \"source_id\": null, \"source_type\": \"ground\", \"user_id\": 140, \"water\": 0, \"year\": 2017}",
"date_edited": "2017-02-27T20:25:29.359834",
"id": 66588,
"record_id": 172812,
"user_id": 140
}
],
"id": 172812,
"intensity": 0,
"land_use_type": 3,
"location_id": 272769,
"month": 2,
"ndvi": null,
"ndvi_mean": null,
"protected": false,
"rating": 0,
"scale": -1,
"source_class": null,
"source_description": "mobile_application",
"source_id": null,
"source_type": "ground",
"user_id": 140,
"water": 0,
"year": 2017
}
],
...
}
一個字符串謝謝kat1330;) –
沒問題:)請注意,你必須處理結果恰當,因爲'。單()'拋出一個異常如果序列是空的或者有很多! – kat1330
是否有任何其他方式來做單旁邊() –