Having this JSON structure :
[
{
"Id": 885758,
"IssueId": 611932,
"Pinpoint": {
"Name": null,
"Position": {
"X": -32.452857971191406,
"Y": -14.971426010131836,
"Z": 9.111014366149902
},
"Element1": null,
"Element2": null
}
},
{
"Id": 885764,
"IssueId": 611932,
"Pinpoint": {
"Name": null,
"Position": {
"X": -21.042057037353516,
"Y": -21.742080688476562,
"Z": 7.72857141494751
},
"Element1": null,
"Element2": null
},
},
{
"Id": 885765,
"IssueId": 611932,
"Pinpoint": null
}
]
I want to be able to obtain a List of JToken containing all Pinpoints that are not null
So basically something like this :
{
"Pinpoint": {
"Name": null,
"Position": {
"X": -32.452857971191406,
"Y": -14.971426010131836,
"Z": 9.111014366149902
},
"Element1": null,
"Element2": null
}
},
{
"Pinpoint": {
"Name": null,
"Position": {
"X": -21.042057037353516,
"Y": -21.742080688476562,
"Z": 7.72857141494751
},
"Element1": null,
"Element2": null
}
}
Image here of what a normal LINQ select without the where condition returns :

This is what I tried so far with related errors / exceptions :
//Cannot access child value on Newtonsoft.Json.Linq.JValue
List<JToken> results = JArray.Parse(response.Content)
.Select(x => x["Pinpoint"])
.Where(x => x["Pinpoint"] != null)
.ToList();
//Object reference not set to an instance of an object.
List<JToken> results = JArray.Parse(response.Content)
.Select(x => x["Pinpoint"])
.Where(x => x["Pinpoint"].HasValues)
.ToList();
//Object reference not set to an instance of an object.
List<JToken> results = JArray.Parse(response.Content)
.Select(x => x["Pinpoint"])
.Where(x => x["Pinpoint"].Type != JTokenType.Null)
.ToList();
Whereclauses before yourSelectclause. Once you've done.Select(x => x["Pinpoint"])your current item will be the value ofx["Pinpoint"]so you can't dox => x["Pinpoint"] != nullsubsequently. Or keep theWhereclause first and do.Where(p => !p.IsNullOrEmpty())next, whereIsNullOrEmpty()is from the linked question Checking for empty or null JToken in a JObject.JsonExtensions.IsNullOrEmpty(this JToken token)here: dotnetfiddle.net/INCWaq. Do you need a separate answer or is a duplicate OK?JTokenwill be returned when the value isn't present at all in the JSON. A non-nullJTokenwill be returned with typeJTokenType.Nullwhen the value was found in the JSON but the value itself was null. I.e. if you dox["Pinpoint"]then if your JSON object looks like{}you will get back null but if your JSON object looks like{"Pinpoint":null}you will get back aJValuewithJTokenType.Null. So you must check for both. For details see Strange behavior in json.net: why is a null JToken replaced with a non-null value?.