1

i'm having a problem with saving my results to file. I have 2 Arraylists

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

with data format like this:

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

I want to save this data to JSON file format like this:

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

I tried following code to create first object

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

And i end up with results:

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

Why i'm getting "map" and "myArrayList" and how i can avoid/remove it to get what i want?

So, what i need to do to get format i need? This occurs only then i execute put(), but i dont know other ways to create structure like i need.

1 Answer 1

2

The problem is you are trying to directly store your ArrayList<List<Integer>> into a JSONArray. GSON is trying to store an array of List<Integer> objects and it don't know how to do that without creating JSONObject to hold it.

To solve this simply loop through the arrays, create JSONArray objects for each dimention and store them into an object.

    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;
}

The above returns a JSONObject that looks like this:

{"collocation":{"first":[[10,20],[3,6]],"second":[[80,76],[12,65]]}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.