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?
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.
[{"userName":"RandomDiscord Name","permissions":"read"},{"userName":"RandomDiscord Name1","permissions":"read2"}]
{"CustomObject":[{"userName":"RandomDiscord Name","permissions":"read"},{"userName":"RandomDiscord Name1","permissions":"read2"}]}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.