[英]Adding elements to array list - Java
I have a class file我有一个 class 文件
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 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.在 JSON output 中有多个 id,我试图将它们存储在一个列表中,但它只添加第一个(“1”),我如何将它们存储在一个列表中。 Please help
请帮忙
The problem is that you iterate over the list of names, and inside the for loop you create a new ArrayList
during every iteration!问题是您遍历名称列表,并在 for 循环中在每次迭代期间创建一个新的
ArrayList
! You want to create your ArrayList
outside of the loop:您想在循环外创建
ArrayList
:
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);
Each iteration of the loop is creating a new id
list.循环的每次迭代都在创建一个新的
id
列表。 Declare that list outside of the loop and it will add the elements to it.在循环之外声明该列表,它将向其中添加元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.