【问题标题】:Getting 'Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken' when retrieving items from JSON从 JSON 检索项目时获取“无法将 Newtonsoft.Json.Linq.JObject 转换为 Newtonsoft.Json.Linq.JToken”
【发布时间】:2018-09-11 17:03:14
【问题描述】:

当有以下代码时

var TermSource =
token.Value<JArray>("annotations")
     .Values<string>("Term Source")
     .FirstOrDefault();

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

"annotations": [
  {
     "Preferred Term": "Text1"
  },
  {
     "Term Source": "Text2"
  }
],

但是,当运行以下行时

var country_code_iso3166_alpha2 =
    token.Value<JArray>("datatype_properties")
         .Values<string>("country_code_iso3166_alpha2")
         .FirstOrDefault();

对于以下 JSON 块

"datatype_properties": {
  "country_name_iso3166_short": [
    "Text Text"
  ],
  "country_code_iso3166_alpha2": [
    "txt1"
  ],
  "country_code_iso3166_alpha3": [
    "txt2"
  ],
  "country_code_un_numeric3": [
    "10"
  ]

我收到以下错误

'无法将 Newtonsoft.Json.Linq.JObject 转换为 Newtonsoft.Json.Linq.JToken'

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

【问题讨论】:

    标签: c# json linq


    【解决方案1】:

    您正在尝试访问datatype_properties,就好像它是一个数组一样。不是 - 它是另一个具有属性 country_code_iso3166_alpha3 的对象,该属性具有数组值。

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

    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);
        }
    }
    

    【讨论】:

    • 非常感谢您的帮助,先生!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多