snaggs snaggs - 3 months ago 23
Java Question

How to convert automatically list of objects to JSONArray with Gson library in java?

Lets say I have following list of custom object:

ArrayList<GroupItem>
where
GroupItem
is some class that has
int
and
String
variables.

I tried so far
Gson
library but it's not exactly what I want.

ArrayList<GroupItem> groupsList = /* ... */
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(groupsList, new TypeToken<ArrayList<GroupItem>>() {}.getType());

JsonArray jsonArray = element.getAsJsonArray();


My goal is to get
JSONArray
(org.Json.JSONArray) somehow. Any ideas?

[EDIT]

My project is Android with Cordova that has API based on
org.Json.JSONArray


ANd I thought to write some generic way to convert instances to
JSONArray
/
JSONObject


Thanks,

Answer

You don't need gson. There's a constructor that takes a collection, so just:

ArrayList<GroupItem> groupsList =... ;
JSONArray JSONArray = new JSONArray(groupsList);
Comments