gpt4 book ai didi

java - 如何在将 ArrayList> 添加到 JSONArray 然后添加到 JSONObject 时修复属性名称

转载 作者:行者123 更新时间:2023-11-30 01:56:22 26 4
gpt4 key购买 nike

我在将结果保存到文件时遇到问题。我有 2 个数组列表

ArrayList<List<Integer>>positions 
ArrayList<List<Integer>>positions2

数据格式如下:

[[0,32],[39,19],[60,15],...]

我想将此数据保存为 JSON 文件格式,如下所示:

"collocation": {
"first": [[0,32],[39,19],[60,15],...],
"second": [[0,32],[39,19],[60,15],...]}

我尝试使用以下代码来创建第一个对象

JSONArray JsonArray = new JSONArray(positions);
JSONObject Jsonobject = new JSONObject();
Jsonobject.put("first",JsonArray);
String jsooo = new Gson().toJson(Jsonobject);

我最终得到了结果:

{"map":{"first":{"myArrayList":[{"myArrayList":[0,32]},{"myArrayList":[39,19]},{"myArrayList":[60,15]}}

为什么我得到“map”和“myArrayList”以及如何避免/删除它以获得我想要的?

那么,我需要做什么才能获得我需要的格式?只有当我执行 put() 时才会发生这种情况,但我不知道其他方法来创建我需要的结构。

最佳答案

问题是您正在尝试直接存储您的 ArrayList<List<Integer>>进入JSONArray 。 GSON 正在尝试存储 List<Integer> 的数组对象,并且它不知道如何在不创建 JSONObject 的情况下做到这一点握住它。

要解决这个问题,只需循环遍历数组,为每个维度创建 JSONArray 对象并将它们存储到一个对象中。

    public static JSONObject saveValues(ArrayList<List<Integer>> pos1, ArrayList<List<Integer>> pos2)
throws JSONException {
JSONObject obj = new JSONObject();
JSONObject collocation = new JSONObject();
JSONArray first = new JSONArray();
JSONArray second = new JSONArray();

for (int i = 0; i < pos1.size(); i++) {
JSONArray arr = new JSONArray();
for (int j = 0; j < pos1.get(i).size(); j++) {
arr.put(pos1.get(i).get(j));
}
first.put(arr);
}
for (int i = 0; i < pos2.size(); i++) {
JSONArray arr = new JSONArray();
for (int j = 0; j < pos2.get(i).size(); j++) {
arr.put(pos2.get(i).get(j));
}
second.put(arr);
}

collocation.put("first", first);
collocation.put("second", second);
obj.put("collocation", collocation);

return obj;
}

上面返回 JSONObject看起来像这样:

{"collocation":{"first":[[10,20],[3,6]],"second":[[80,76],[12,65]]}}

关于java - 如何在将 ArrayList<List<Integer>> 添加到 JSONArray 然后添加到 JSONObject 时修复属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54372183/

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