I retrieved the following JSON-object. These json array consists of posts. As can be seen from the below, each post has a userId, id, title and a body. Now I need to iterate through this json and get the id of the posts IF the userId is 5 (in this case all four id's will be stored because in all of them the userId is 5
[
{
"userId": 5,
"id": 21,
"title": "A title",
"body": "A body"
},
{
"userId": 5,
"id": 52,
"title": "B title",
"body": "B body"
},
{
"userId": 5,
"id": 13,
"title": "C title",
"body": "C body"
},
{
"userId": 5,
"id": 44,
"title": "D title",
"body": "D body"
},
]
and then I need to store the id values in an array like this: postIds = [21, 52, 13, 44]
So far I have done this
GetPosts[] getPosts = getPostResponse.as(GetPosts[].class);
String[] userPostIds;
for (int i = 0; i < getPosts.length; i++) {
if(getPosts[0].getId().equals(userId)) {
}
}
Then I tried to write a for loop like this but I know it is wrong. Maybe the statement in if parentheses is true, but for loop needs to be something else and I need to write something inside the if statement but I cannot progress here.
Edit: I now modified the for/if loop like this:
for (int i = 0; i < getPosts.length; i++) {
Integer userPostIds = null;
if (getPosts[i].getId().equals(userId)) {
userPostIds = getPosts.getId();
}
System.out.println(userPostIds);
}
But this time userPostIds is printed like this:
null
null
null
null
whereas I was expecting it to be:
21
52
13
44
0as the index into your array, where you need to usei.