添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

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

for the following JSON block

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

I get the following error

'Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken'

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

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

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.