Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

gson

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,

like image 720
snaggs Avatar asked Mar 01 '14 19:03

snaggs


3 Answers

This way is worked for me:

Convert all list to String.

String element = gson.toJson(
                    groupsList,
           new TypeToken<ArrayList<GroupItem>>() {}.getType());

Create JSONArray from String:

    JSONArray list = new JSONArray(element);
like image 100
snaggs Avatar answered Nov 12 '22 15:11

snaggs


The org.json based classes included in Android don't have any features related to converting Java POJOs to/from JSON.

If you have a list of some class (List<GroupItem>) and you absolutely need to convert that to a org.json.JSONArray you have two choices:

A) Use Gson or Jackson to convert to JSON, then parse that JSON into a JSONArray:

List<GroupItem> list = ...
String json = new Gson().toJson(list);
JSONArray array = new JSONArray(json);

B) Write code to create the JSONArray and the JSONObjects it will contain from your Java objects:

JSONArray array = new JSONArray();
for (GroupItem gi : list)
{
    JSONObject obj = new JSONObject();
    obj.put("fieldName", gi.fieldName);
    obj.put("fieldName2", gi.fieldName2);
    array.put(obj);
}
like image 7
Brian Roach Avatar answered Nov 12 '22 13:11

Brian Roach


Why do you want to use GSON to convert to an org.json class? Nor do you need to write any custom code to get a JSONArray. The org.json api provides a way to do it.

  LinkedList list = new LinkedList();
  list.add("foo");
  list.add(new Integer(100));
  list.add(new Double(1000.21));
  list.add(new Boolean(true));
  list.add(null);
  JSONArray jsonArray = new JSONArray(list);
  System.out.print(jsonArray);
like image 3
jeremyjjbrown Avatar answered Nov 12 '22 13:11

jeremyjjbrown