从 JSON 检索项目时获取“无法将 Newtonsoft.Json.Linq.JObject 转换为 Newtonsoft.Json.Linq.JToken”

Mik*_*ail 3 c# linq json

当有以下代码时

var TermSource =
token.Value<JArray>("annotations")
     .Values<string>("Term Source")
     .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

我能够获得以下 JSON 块的结果

"annotations": [
  {
     "Preferred Term": "Text1"
  },
  {
     "Term Source": "Text2"
  }
],
Run Code Online (Sandbox Code Playgroud)

但是,在运行以下行时

var country_code_iso3166_alpha2 =
    token.Value<JArray>("datatype_properties")
         .Values<string>("country_code_iso3166_alpha2")
         .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

对于以下 JSON 块

"datatype_properties": {
  "country_name_iso3166_short": [
    "Text Text"
  ],
  "country_code_iso3166_alpha2": [
    "txt1"
  ],
  "country_code_iso3166_alpha3": [
    "txt2"
  ],
  "country_code_un_numeric3": [
    "10"
  ]
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

'不能将 Newtonsoft.Json.Linq.JObject 转换为 Newtonsoft.Json.Linq.JToken'

我应该如何修复 LINQ 语句以检索“country_code_iso3166_alpha2”数据的值

Jon*_*eet 7

您正在尝试将datatype_properties其作为数组进行访问。它不是 - 它是另一个country_code_iso3166_alpha3具有数组值的属性的对象。

您可以Value使用JObject类型参数调用该方法来获取对象,然后Value再次使用JArray类型参数来获取数组。这是一个简短但完整的示例:

using System;
using System.Linq;
using Newtonsoft.Json.Linq;

class Test
{
    static void Main()
    {
        string json = @"{
  'datatype_properties': {
    'country_name_iso3166_short': [
      'Text Text'
    ]
  }
}".Replace("'", "\"");
        JObject parent = JObject.Parse(json);
        string countryName = parent["datatype_properties"]
            .Value<JArray>("country_name_iso3166_short")
            .Values<string>()
            .FirstOrDefault();
        Console.WriteLine(countryName);
    }
}
Run Code Online (Sandbox Code Playgroud)