0

I have a class file

public class Name {
    private String id;

    public String getId() {
        return id;
    }
}

This is the test file

CollectionType javaType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Name.class);
ArrayList<Names> nameList = mapper.readValue(json, javaType);
for (Names nameValue : nameList) {
    List<String> id = new ArrayList<>();
    id.add(nameValue.getId());
System.out.println(id);

json

[{"id":"1"},{"id":"2"}]

In the JSON output there is more than one id, and I am trying to store them in one list but it only adds the first one ("1"), how do I store both in one list. Please help

2
  • Where are you closing the for loop? Your identation doesn't help too much to figure it out. In every iteration you're creating a new List, take the id outside the for loop Commented Apr 29, 2021 at 21:20
  • you should construct your List outside of the loop. Commented Apr 29, 2021 at 21:21

2 Answers 2

1

The problem is that you iterate over the list of names, and inside the for loop you create a new ArrayList during every iteration! You want to create your ArrayList outside of the loop:

CollectionType javaType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Name.class);
ArrayList<Names> nameList = mapper.readValue(json, javaType);
List<String> id = new ArrayList<>();
for (Names nameValue : nameList) {
    id.add(nameValue.getId());
}
System.out.println(id);
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thank you for the answer. Is there a way to just print the last list without printing it twice as [1], [1,2]
Actually got it, just moved the println from for loop, thank you!
0

Each iteration of the loop is creating a new id list. Declare that list outside of the loop and it will add the elements to it.

Comments

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.