C# linq to json 如何读取数组中的属性值

标签 c# json linq

我有一个 JSON 文件,我想在其中获取数组属性 records 中的属性值 land_use_type。我的第一次尝试是将 Linq to JSON 与 Newtonsoft 引用一起使用,但 LINQ 总是向我发送此消息:

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
}
 ],
 ...

}

最佳答案

你可以在你的情况下试试这个:

var Land_use = jsondata["records"].Values("land_use_type").Single().ToString();

Land_use 将为 "3"

或者你可以这样做:

var Land_use = var Land_use = jsondata["records"].Values("land_use_type").FirstOrDefault()?.Value<string>();

关于C# linq to json 如何读取数组中的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42499235/

相关文章:

C#构造函数和构造对象的类型

javascript - 获取 JSON 数据 : Syntax error

java从json中读取日期

c# - 如何构建这个 LINQ 表达式?

c# - 在 C# 中使用 LINQ 解析 XML

c# - 内存不足和溢出异常创建小数组

C#:将多个图像保存到一个文件中

c# - 在 C# 中使用 Linq 计算评分平均值

c# - 在 Newtonsoft 的深层嵌套 JSON 中查找深层子元素的更简单方法?

json - 无法写入内容 : failed to lazily initialize a collection of role