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

时间:2019-01-25 20:13:17

标签: java json gson

我将结果保存到文件时遇到问题。我有2个Arraylists

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()时才会发生这种情况,但是我不知道其他创建所需结构的方法。

1 个答案:

答案 0 :(得分:2)

问题是您正在尝试将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]]}}