英文:
How to convert list of Json string to JsonObject using Gson
问题
我有一个 JSON 字符串列表:List<String> jsonStringList
,我想使用 Gson 将它们转换为单个 JsonObject,我想知道最佳方法是什么?
我知道我可以逐个解析它们,就像这样:
for (String jsonString : jsonStringList) {
JsonElement parsed = new JsonParser().parse(jsonString);
}
但是我该如何将它们合并在一起?最佳方法是什么?
英文:
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
得分: 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());
输出结果:
[
{"userName":"RandomDiscord Name","permissions":"read"},
{"userName":"RandomDiscord Name1","permissions":"read2"}
]
{"CustomObject":[{"userName":"RandomDiscord Name","permissions":"read"},{"userName":"RandomDiscord Name1","permissions":"read2"}]}
英文:
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<String> 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"}]}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论