gpt4 book ai didi

java - 使用 GSON 创建合并的 JSON

转载 作者:行者123 更新时间:2023-11-29 21:11:03 25 4
gpt4 key购买 nike

我发现了大量使用 GSON 将单个对象或该单个对象的列表转换为其各自的 JSON 的示例。很容易做到。即使对象具有对象作为其属性,这仍然是微不足道的。

但假设我有 5 个感兴趣的对象(名称、公司、颜色、数字、糖果),它们之间完全没有关系。所以我进行了数据库调用,现在我的代码中有 5 个包含上述所有内容的列表。

现在,我如何将这些列表放入父名称为“items”并包含上述所有子项的 JSON 数组?所以一个 parent “项目”,有 5 个 child (每个 child 都是彼此的 sibling )。

使用 GSON(或不使用??)构建这样的树或结构的合适方法是什么?我注意到 GSON 中有很多,例如 JSONArray 等,但无法弄明白。

非常感谢!

最佳答案

是的,你可以。您必须先构建自己的序列化程序。例如:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public static String toJson(List<Item> items){

try{

JSONObject jsonObj = new JSONObject();

JSONArray jsonArr = new JSONArray();

for(Item i : items){
JSONObject itemObj = new JSONObject();
itemObj.put("names", i.getName());
itemObj.put("companies", i.getCompanies());
itemObj.put("colors", i.getColors());
itemObj.put("numbers", i.getNumbers());
itemObj.put("candy", i.getCandy());
jsonArr.put(itemObj);
}

jsonObj.put("items", jsonArr);

return jsonObj.toString();

} catch(JSONException ex){
ex.printStackTrace();
}

return null;
}

关于java - 使用 GSON 创建合并的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22827546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com