Koray
Koray

Reputation: 39

Iterate through a Json object and store some values in an array

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

Upvotes: 0

Views: 914

Answers (2)

armitus
armitus

Reputation: 748

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).

Upvotes: 0

Paweł Lenczewski
Paweł Lenczewski

Reputation: 126

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());
}

Upvotes: 1

Related Questions