Getting 'Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken' when retrieving items from JSON

前端 未结 1 884
执笔经年
执笔经年 2021-01-23 01:19

When having the following code

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


        
相关标签:
1条回答
  • 2021-01-23 02:09

    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.

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题