Below code should work for your case.
List<Customer> customerList = CustomerDB.selectAll();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(customerList, new TypeToken<List<Customer>>() {}.getType());
if (! element.isJsonArray() ) {
// fail appropriately
throw new SomeException();
}
JsonArray jsonArray = element.getAsJsonArray();
Heck, use List interface to collect values before converting it JSON Tree.
Below code should work for your case.
List<Customer> customerList = CustomerDB.selectAll();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(customerList, new TypeToken<List<Customer>>() {}.getType());
if (! element.isJsonArray() ) {
// fail appropriately
throw new SomeException();
}
JsonArray jsonArray = element.getAsJsonArray();
Heck, use List interface to collect values before converting it JSON Tree.
As an additional answer, it can also be made shorter.
List<Customer> customerList = CustomerDB.selectAll();
JsonArray result = (JsonArray) new Gson().toJsonTree(customerList,
new TypeToken<List<Customer>>() {
}.getType());
Definitely the easiest way to do that is using Gson's default parsing function fromJson().
There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType (e.g., any List), which is fromJson(JsonElement json, Type typeOfT).
In your case, you just need to get the Type of a List<String> and then parse the JSON array into that Type, like this:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> yourList = new Gson().fromJson(yourJson, listType);
In your case yourJson is a JsonElement, but it could also be a String, any Reader or a JsonReader.
You may want to take a look at Gson API documentation.
Below code is using com.google.gson.JsonArray.
I have printed the number of element in list as well as the elements in List
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
static String str = "{ "+
"\"client\":\"127.0.0.1\"," +
"\"servers\":[" +
" \"8.8.8.8\"," +
" \"8.8.4.4\"," +
" \"156.154.70.1\"," +
" \"156.154.71.1\" " +
" ]" +
"}";
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(str);
JsonArray jsonArr = jo.getAsJsonArray("servers");
//jsonArr.
Gson googleJson = new Gson();
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
System.out.println("List size is : "+jsonObjList.size());
System.out.println("List Elements are : "+jsonObjList.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT
List size is : 4
List Elements are : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]
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);
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);
}
There is a sample from google gson documentation on how to actually convert the list to json string:
CopyType listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");
Gson gson = new Gson();
String json = gson.toJson(target, listType);
List<String> target2 = gson.fromJson(json, listType);
You need to set the type of list in toJson method and pass the list object to convert it to json string or vice versa.
If response in your marshal method is a DataResponse, then that's what you should be serializing.
CopyGson gson = new Gson();
gson.toJson(response);
That will give you the JSON output you are looking for.
Here's a comprehensive example on how to use Gson with a list of objects. This should demonstrate exactly how to convert to/from Json, how to reference lists, etc.
Test.java:
import com.google.gson.Gson;
import java.util.List;
import java.util.ArrayList;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class Test {
public static void main (String[] args) {
// Initialize a list of type DataObject
List<DataObject> objList = new ArrayList<DataObject>();
objList.add(new DataObject(0, "zero"));
objList.add(new DataObject(1, "one"));
objList.add(new DataObject(2, "two"));
// Convert the object to a JSON string
String json = new Gson().toJson(objList);
System.out.println(json);
// Now convert the JSON string back to your java object
Type type = new TypeToken<List<DataObject>>(){}.getType();
List<DataObject> inpList = new Gson().fromJson(json, type);
for (int i=0;i<inpList.size();i++) {
DataObject x = inpList.get(i);
System.out.println(x);
}
}
private static class DataObject {
private int a;
private String b;
public DataObject(int a, String b) {
this.a = a;
this.b = b;
}
public String toString() {
return "a = " +a+ ", b = " +b;
}
}
}
To compile it:
javac -cp "gson-2.1.jar:." Test.java
And finally to run it:
java -cp "gson-2.1.jar:." Test
Note that if you're using Windows, you'll have to switch : with ; in the previous two commands.
After you run it, you should see the following output:
[{"a":0,"b":"zero"},{"a":1,"b":"one"},{"a":2,"b":"two"}]
a = 0, b = zero
a = 1, b = one
a = 2, b = two
Keep in mind that this is only a command line program to demonstrate how it works, but the same principles apply within the Android environment (referencing jar libs, etc.)
My version of gson list deserialization using a helper class:
public List<E> getList(Class<E> type, JSONArray json) throws Exception {
Gson gsonB = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
return gsonB.fromJson(json.toString(), new JsonListHelper<E>(type));
}
public class JsonListHelper<T> implements ParameterizedType {
private Class<?> wrapped;
public JsonListHelper(Class<T> wrapped) {
this.wrapped = wrapped;
}
public Type[] getActualTypeArguments() {
return new Type[] {wrapped};
}
public Type getRawType() {
return List.class;
}
public Type getOwnerType() {
return null;
}
}
Usage
List<Object> objects = getList(Object.class, myJsonArray);
Problem is caused by comma at the end of (in your case each) JSON object placed in the array:
{
"number": "...",
"title": ".." , //<- see that comma?
}
If you remove them your data will become
[
{
"number": "3",
"title": "hello_world"
}, {
"number": "2",
"title": "hello_world"
}
]
and
Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);
should work fine.
Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);
class Wrapper{
int number;
String title;
}
Seems to work fine. But there is an extra , Comma in your string.
[
{
"number" : "3",
"title" : "hello_world"
},
{
"number" : "2",
"title" : "hello_world"
}
]