简体   繁体   English

如何在JsonObject中存储嵌套的ArrayList

[英]How to store a nested ArrayList in a JsonObject

So I have this ArrayList existing of school classes and each class has an ArrayList containing ArrayLists of additional values. 所以我有这个ArrayList现有的学校类,每个类都有一个ArrayList包含其他值的ArrayLists。 I would have to declare it like this 我必须这样宣布它

ArrayList<ArrayList<String>>

I'll be looping through this rota of classes and will add this in a JsonObject using the JsonObjectBuilder. 我将循环遍历这些类的循环,并将使用JsonObjectBuilder在JsonObject中添加它。 Here's an example. 这是一个例子。

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

Now, how would I go about storing that ArrayList in the JsonObject so that I can use this later on? 现在,我将如何将该ArrayList存储在JsonObject中,以便以后可以使用它? (I'll be retrieving this JsonObject with Polymer, but being able to store the array first would be the first step. (我将使用Polymer检索此JsonObject,但是能够首先存储数组将是第一步。

Thank in advance! 预先感谢!

You can use jackson library to do this easily. 您可以使用jackson库轻松完成此操作。 That library will not need you to mess around with Json* classes that you have right now. 那个库不需要你搞乱你现在拥有的Json *类。 Try this - 尝试这个 -

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

For me, it printed [["2","3"],["4","6"],["6","9"],["8","12"],["10","15"],["12","18"],["14","21"],["16","24"],["18","27"],["20","30"]] 对我来说,它打印[["2","3"],["4","6"],["6","9"],["8","12"],["10","15"],["12","18"],["14","21"],["16","24"],["18","27"],["20","30"]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM