0

i'm searching for an option to add multiple values to a JSONArray and add this into another JSONArray without creating multiple variables. For example:

    JSONArray array1 = new JSONArray();
    JSONArray array2 = new JSONArray();
    array2.add("ex1");
    array2.add("ex2");
    array2.add("ex3");
    array1.add(array2);

into something like:

    JSONArray array1 = new JSONArray();
    array1.add(new JSONArray().addAll(Arrays.asList("ex1","ex2","ex3")));
    array1.add(new JSONArray().addAll(Arrays.asList("ex4","ex5","ex6")));

is there a way to do this? Thanks guys

1 Answer 1

1

It can be done using gson:

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>

Here is a running code:

package com.test;

import java.util.Arrays;
import java.util.List;

import com.google.gson.JsonArray;

public class JArray {

    public static void main(String[] args) {
        JsonArray array1 = new JsonArray();

        array1.addAll(getJsonArrayFromList(Arrays.asList("ex1", "ex2", "ex3")));
        array1.addAll(getJsonArrayFromList(Arrays.asList("ex4", "ex5", "ex6")));

        System.out.println("array1 = " + array1);
    }

    public static JsonArray getJsonArrayFromList(List<String> list) {
        JsonArray array = new JsonArray();
        for (String s : list) {
            array.add(s);
        }
        return array;
    }

}

Output:

array1 = ["ex1","ex2","ex3","ex4","ex5","ex6"]
Sign up to request clarification or add additional context in comments.

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.