0

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
11
  • Please edit your question to include your code, and explain exactly where you are stuck. Read How to Ask. Commented Jul 9, 2021 at 22:25
  • @Koray, we need a minimal reproducible example of what you've done so far. See tgdavies' comment. Commented Jul 9, 2021 at 22:39
  • Presuming you have the data stored in a String, I would recommend using the Jackson-Core library github.com/FasterXML/jackson-core. This has all the necessary tools for serialization/de-serialization of JSON objects. You can iterate through those objects once de-serialized and collect the Ids. Commented Jul 9, 2021 at 22:40
  • @tgdavies edited, thanks Commented Jul 9, 2021 at 23:05
  • 1
    Your for loop is fine, except that you are always using 0 as the index into your array, where you need to use i. Commented Jul 9, 2021 at 23:07

2 Answers 2

1

Let's assume that you have stored your JSON as a String. You can use Jackson object mapper to map JSON to Object.

  private static String JSON = "[\n" +
        "  {\n" +
        "    \"userId\": 5,\n" +
        "    \"id\": 21,\n" +
        "    \"title\": \"A title\",\n" +
        "    \"body\": \"A body\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"userId\": 5,\n" +
        "    \"id\": 52,\n" +
        "    \"title\": \"B title\",\n" +
        "    \"body\": \"B body\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"userId\": 5,\n" +
        "    \"id\": 13,\n" +
        "    \"title\": \"C title\",\n" +
        "    \"body\": \"C body\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"userId\": 5,\n" +
        "    \"id\": 44,\n" +
        "    \"title\": \"D title\",\n" +
        "    \"body\": \"D body\"\n" +
        "  }\n" +
        "]";

You need to create object for mapping:

public class Foo {
  private Integer userId;
  private Integer id;
  private String title;
  private String body;
  // getters
  // setters
}

Then you can map your JSON to list of objects:

 private static List<Foo> mapJsonToObject() {
    var om = new ObjectMapper();
    List<Foo> list = null;
    try {
         list = Arrays.asList(om.readValue(JSON, Foo[].class));
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return list;
}

In the end you need to iterate through this list to get all ids.

  public static void main(String[] args) {
    var list = mapJsonToObject();
    var ids = list.stream().map(Foo::getId).collect(Collectors.toList());
    System.out.println(ids.toString());
}
Sign up to request clarification or add additional context in comments.

3 Comments

The OP should be aware that this uses the Jackson-Core ObjectMapper.
Additionally, Baeldung has an excellent tutorial on this. baeldung.com/jackson-object-mapper-tutorial
I have already done this steps before I created the post using jackson.core, deserialized from json to java, created the object for mappers (getters setters). The problem is to be able to write the for/if statement to get the data I want, I can not do it
0

Thankfully, the hard part (deserialization) is complete per the OP. Therefore, to iterate over the object list, I recommend something similar to the following, presuming that the post.getId returns a String (Otherwise, you may need to do a cast conversion)

    Log.info("Store all the posts of the user");
    GetPosts[] getPosts = getPostResponse.as(GetPosts[].class);

    ArrayList<Integer> userIdsFromPosts = new ArrayList<Integer>();
    
    if(getPosts != null) { // Avoiding a Possible NPE in list iteration...Just in case ;)
        for (GetPosts post : getPosts) {
            Integer currentUserId = post.getId();
            if (!userIdsFromPosts.contains(currentUserId)) {
                userIdsFromPosts.add(currentUserId);
            }
        }
    }
    
    return userIdsFromPosts;

One final note, if you are expecting a VERY large number of posts, then you should use a HashSet instead of ArrayList for performance reasons (when we run the .contains() method, each element of the ArrayList is iterated over).

4 Comments

post.getId() returns integer
and no I dont expect larger number of post. There are only four posts as it is in the question :)
Let me know how it goes. Happy Programming :)
I had presumed that you were trying to process some logic if a specific userId was found. Rereading the OP....Ah, I see you just need the values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.