从JSON检索项目时,获取“无法将Newtonsoft.Json.Linq.JObject转换为Newtonsoft.Json.Linq.JToken" [英] Getting 'Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken' when retrieving items from 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
类型的参数调用Value
以获取数组.这是一个简短但完整的示例:
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);
}
}
这篇关于从JSON检索项目时,获取“无法将Newtonsoft.Json.Linq.JObject转换为Newtonsoft.Json.Linq.JToken"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!