所以我有这个ArrayList在学校班级中存在,每个班级都有一个ArrayList,其中包含其他值的ArrayLists。我必须像这样声明它
ArrayList<ArrayList<String>>
我将遍历这一系列的类,并将使用JsonObjectBuilder将其添加到JsonObject中。这是一个例子。
JsonArrayBuilder arrBuilder = Json.createArrayBuilder();
for (Rota class : rotaArray) {
JsonObjectBuilder builderRota = Json.createObjectBuilder();
String example = class.getExample();
//This is where I get the ArrayList of each class.
ArrayList<ArrayList<String>> arrExample = class.getArrExample();
builderRota
.add("example", example)
//This is where I'm stuck since the builder expects it to have a String as value instead of an ArrayList.
.add("arr", arrExample);
arrBuilder.add(builderRota);
}
现在,我该如何将ArrayList存储在JsonObject中,以便以后使用? (我将使用Polymer检索此JsonObject,但首先要存储数组将是第一步。
提前谢谢!
答案 0 :(得分:0)
您可以使用jackson库轻松完成此操作。该库将不再需要您弄乱您现在拥有的Json *类。试试这个-
@org.junit.jupiter.api.Test
public void testJson() throws JsonProcessingException {
ArrayList<ArrayList<String>> input = new ArrayList<>();
for(int i = 1; i<=10; i++) {
input.add(new ArrayList<>(Arrays.asList(String.valueOf(2*i),String.valueOf(3*i))));
}
// This converts the Array to Json
// This class is part of jackson library - https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.9.8
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsString(input));
}
对我来说,它打印了[["2","3"],["4","6"],["6","9"],["8","12"],["10","15"],["12","18"],["14","21"],["16","24"],["18","27"],["20","30"]]