Meeesh Meeesh - 1 month ago 7
Java Question

In Java, how do I most efficiently find an array within a JSON array based on the value of an element of the subarray?

So this is an example piece of JSON data that I'm working with.

{"season":"2016",
"week":"",
"positions":{
"QB":[
{
"id":"2505245",
"esbid":"PAL249055",
"gsisPlayerId":"00-0021429",
"firstName":"Carson",
"lastName":"Palmer",
"teamAbbr":"ARI",
"opponentTeamAbbr":"",
"position":"QB",
"rank":"22",
"statsLine":"",
"stats":
{
"PassYds":false,
"PassTDs":false,
"Int":false,
"RushYds":false,
"RushTDs":false,
"RecYds":false,
"RecTds":false,
"FumTD":false,
"TwoPt":false,
"FumLost":false
},
"pts":"85.00",
"projectedPts":"277.46",
"status":""
},
{
"id":"2495748",
"esbid":"STA482517",
"gsisPlayerId":"00-0025430",
"firstName":"Drew",
"lastName":"Stanton",
"teamAbbr":"ARI",
"opponentTeamAbbr":"",
"position":"QB",
"rank":"42",
"statsLine":"",
"stats":
{
"PassYds":false,
"PassTDs":false,
"Int":false,
"RushYds":false,
"RushTDs":false,
"RecYds":false,
"RecTds":false,
"FumTD":false,
"TwoPt":false,
"FumLost":false
},
"pts":"11.06",
"projectedPts":"7.36",
"status":""}]
}
}


Now I have a huge list with hundreds of different players set up like this and I would like to be able to get the data for a single player. In this case, let's say I want to find the stats for Carson Palmer. That would mean I want to look in the QB JSON array to find a sub array which includes
firstName:Carson
and
lastName:Palmer
.

How would I do this with a library like GSON?

Answer

JsonPath

From all positions, find all elements with first name Carson, last name Palmer

$.positions[*][?(@.firstName == "Carson" && @.lastName == "Palmer")]

Add .stats to the end of that or parse it out yourself from that object

Note: that returns an array. Multiple players could have that name.


Alternatively, you are getting this data from some server, and you should perform the player search server-side

Comments