Reputation: 856
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();
Upvotes: 0
Views: 494
Reputation: 43860
try this
List<JObject> pinPoints = JArray.Parse(json).Where(p => (p["Pinpoint"] as JObject) != null)
.Select(p => (JObject)p["Pinpoint"]).ToList();
UPDATE
thanks to @dbc, there is a shorthand
JArray.Parse(json).Select(p => p["Pinpoint"]).OfType<JObject>().ToList();
Upvotes: 1