0

I have a list of Json string: List<String> jsonStringList, I want to convert it to a single JsonObject using Gson, may I know what is the best way to do it?

I know I can parse them one by one like:

for (String jsonString : jsonStringList) {
    JsonElement parsed = new JsonParser().parse(jsonString);
}

But how do I join them together? What is the best way to do it?

1 Answer 1

1
        String s1 = "{\n" +
                "    \"userName\": \"RandomDiscord Name\",\n" +
                "    \"permissions\": \"read\"\n" +
                "  }";
        String s2 = "{\n" +
                "    \"userName\": \"RandomDiscord Name1\",\n" +
                "    \"permissions\": \"read2\"\n" +
                "  }";
        List<String> jsonStringList = Arrays.asList(new String[]{s1, s2});
        JSONArray arr = new JSONArray();
        for (String jsonString : jsonStringList) {
            JsonElement obj = new JsonParser().parse(jsonString);
            arr.add(obj);
        }
        String jsonString = arr.toString();
        System.out.println(jsonString);

        JSONObject obj = new JSONObject();
        try {
            obj.put("CustomObject", arr);
        } catch(JSONParseException e) {
            e.printStackTrace();
        }
        System.out.println(obj.toString());

Try to use JSONArray and while iterating List just add that object into JsonArray.

For above code, i am getting below output O/P

[{"userName":"RandomDiscord Name","permissions":"read"},{"userName":"RandomDiscord Name1","permissions":"read2"}]
{"CustomObject":[{"userName":"RandomDiscord Name","permissions":"read"},{"userName":"RandomDiscord Name1","permissions":"read2"}]}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi I want to convert it to gson.JsonObject, I tried your code with JsonArray then I do jsonArray.getAsJsonObject() but throw an Exception: com.google.gson.JsonSyntaxException: Response did not contain a JSON Object may I know how can I fix it?

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.