Question39623308 linq-to-json-nullreferenceexception-error-from-a-jtoken-that-could-be-either-a

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;		
					
					
	public class Program
	{
        static string GetJson()
        {
            var json = @"{
    ""?xml"" : {
        ""@version"" : ""1.0"",
        ""@encoding"" : ""UTF-8""
    },
    ""DataFeed"" : {
        ""@FeedName"" : ""AdminData"",
        ""People"" : [{
                ""id"" : ""63"",
                ""active"": ""1"",
                ""firstName"" : ""Joe"",
                ""lastName"" : ""Schmoe"",
                ""roleIds"" : {
                    ""int"" : ""4""
                }
            } , {
                ""id"" : ""65"",
                ""active"": ""1"",
                ""firstName"" : ""Steve"",
                ""lastName"" : ""Jobs"",
                ""roleIds"" : {
                    ""int"" : [""4"", ""16"", ""25"", ""20"", ""21"", ""22"", ""17"", ""23"", ""18""]
                }
            } , {
                ""id"" : ""66"",
                ""active"": ""1"",
                ""firstName"" : ""Bill"",
                ""lastName"" : ""Gates"",
                ""roleIds"" : {
                    ""int"" : [""3"", ""16"", ""25"", ""20""]
                }
            }
        ]
    }
}";
            return json;
        }
		
		public static void Main()
		{
            var jsonString = GetJson();

            JObject jsonFeed = JObject.Parse(jsonString);

            var query = from people in jsonFeed.SelectTokens("DataFeed.People")
                               .SelectMany(i => i)
                        let ids = people.SelectToken("roleIds.int")
                        where (int)people["active"] == 1 &&
                            (ids.Type == JTokenType.Array) ?
                                ((int[])ids.ToObject(typeof(int[]))).Any(k => k == 4) :
                                (int)ids == 4
                        select new
                        {
                            Id = (int)people["id"],
                            ResAnFName = (string)people["firstName"],
                            ResAnLName = (string)people["lastName"]
                        };
			
			Console.WriteLine("Query result: ");
			Console.WriteLine(JsonConvert.SerializeObject(query, Formatting.Indented));
		}
	}
;