获取 '无法将 Newtonsoft.Json.Linq.JObject 转换为 Newtonsoft.Json.Linq.JToken'从JSON检索项目时 [英] Getting 'Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken' when retrieving items from JSON

查看:85
本文介绍了获取 '无法将 Newtonsoft.Json.Linq.JObject 转换为 Newtonsoft.Json.Linq.JToken'从JSON检索项目时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有以下代码时

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

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

I am able to get results for the following JSON block

"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'数据的值

How I should fix the LINQ statement to retrieve the value for the 'country_code_iso3166_alpha2' data

推荐答案

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

You're trying to access datatype_properties as if it's an array. It's not - it's another object with a property country_code_iso3166_alpha3 which has an array value.

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

You can call the Value method with a JObject type argument to get the object, then Value again with a JArray type argument to get the array. Here's a short but complete example:

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

这篇关于获取 &amp;#39;无法将 Newtonsoft.Json.Linq.JObject 转换为 Newtonsoft.Json.Linq.JToken&amp;#39;从JSON检索项目时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆