0

I have created an ArrayList and I need to convert it to a JSONarray:

This is how an Object in my ArrayList<model> looks like:

modelList.add(new model("String", 9.99 /*Double*/, null /*Date*/, R.drawable.drawable, R.color.color, 1 /*int*/, 0 /*int*/));
...

this is what I tried so far:

public void saveArrayListtoJSON(ArrayList<Model> modelList) {
        JSONArray myJSONArray = new JSONArray();
            JSONObject obj = new JSONObject();
            obj.put("key", modelList);
            myJSONArray.put(obj);
        }
    }
Daniele
  • 4,163
  • 7
  • 44
  • 95

5 Answers5

2

You can try like this :

  public void saveArrayListtoJSON(ArrayList<Model> modelList) {
        JSONArray myJSONArray = new JSONArray();
        JSONObject obj = new JSONObject();
        for(Model model : modelList){
            try {
                obj.put("key", model);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            myJSONArray.put(obj);
        }
    }

Revert for any error.

Aashish Aadarsh
  • 491
  • 5
  • 7
1

You can use gson as well and just give the arraylist as parameter. But be careful all elements of your model need to be serializable if not use transient to remove object which is not serializable in your model

Gson - putting and getting ArrayList of composite objects

Take a look here too: Deserialize a List<T> object with Gson?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Timo
  • 497
  • 10
  • 21
  • Thanks for the answer Timo. Can you provide me an example on how to use Gson to save and retrieve the arrayList? the `List modelList = new Gson().fromJson(jsonArray, Model.class);` does not work for me. I get `incompatible types` – Daniele May 11 '17 at 10:00
  • http://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type or Model[] models = new Gson().fromJson(jsonArray,Model[].class); – Timo May 11 '17 at 11:48
1

You can try code below:

    public void saveArrayListtoJSON(ArrayList<Model> modelList) {
    JSONArray myJSONArray = new JSONArray();
        JSONObject obj = new JSONObject();
        JSONArray array = new JSONArray();
        for (Model model:modelList) {
            array.put(model.getJson());
        }
        obj.put("key", array);
        myJSONArray.put(obj);
    }
}

I suppose that method getJson() is your method which return JSON object which present Model object

Luc Le
  • 196
  • 9
1

add this Gradle in your build.gradle compile 'com.google.code.gson:gson:2.7'

and then

String str = new Gson().toJson(modelList);
JSONObject jsonObject = new JSONObject(str);
Bhupat Bheda
  • 1,968
  • 1
  • 8
  • 13
0

You can use Gson to convert ArrayList to JSON array

Gson gson = new Gson();
String json = gson.toJson(yourArraylist);
Patrick R
  • 6,621
  • 1
  • 24
  • 27