且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-17 19:40:58

您正在尝试访问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);
    }
}