Reputation: 5713
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,
Upvotes: 12
Views: 76806
Reputation: 4726
Use Jackson for JSON to Object or Object to JSON
See the next link Jackson examples
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
StringWriter stringWriter = new StringWriter();
objectMapper.writeValue(stringWriter, groupsList );
System.out.println("groupsList JSON is\n"+stringWrite);
Upvotes: 3
Reputation: 76898
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 JSONObject
s 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);
}
Upvotes: 7
Reputation: 5713
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);
Upvotes: 22
Reputation: 8009
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);
Upvotes: 3
Reputation: 54781
You don't need gson. There's a constructor that takes a collection, so just:
ArrayList<GroupItem> groupsList =... ;
JSONArray JSONArray = new JSONArray(groupsList);
Upvotes: 1