I use Gson for serialize and deserialize json.
pojo class :
class myData{
public String id;
public String name;
}
and with this code i get that json to pojo class.
public static Object getData(Class clazz) {
String json = "{'name':'john','id':'123'}";
Gson gson = new Gson();
return gson.fromJson(json , clazz);
}
//usage:
myData mdata= (myData) getData(myData.class);
every thing goes fine, in read array from json i have this method:
ArrayList<myData> getDatas() {
ArrayList<myData> mdatas = new ArrayList<>();
String json ="[{'name':'john','code':'123'},{'name':'nick','code':'456'}]";
Type listType = new TypeToken<ArrayList<myData>>() {
}.getType();
if (new Gson().fromJson(json, listType) != null) {
return new Gson().fromJson(json, listType);
} else {
return mdatas;
}
}
that code was fine. but i want to pass any class in getDatas and find that class in json then return list of that class in result.
something like this:
ArrayList<?> getDatas(Class clazz) {
ArrayList<clazz> mdatas = new ArrayList<>(); //this line is the problem
String json = "[{'name':'john','code':'123'},{'name':'nick','code':'456'}]";
//and this line
Type listType = new TypeToken<ArrayList<clazz>>() {
}.getType();
if (new Gson().fromJson(json, listType) != null) {
return new Gson().fromJson(json, listType);
} else {
return mdatas;
}
}
problem is cant use anonymous class in arraylist.
ArrayList<clazz> mdatas = new ArrayList<>();
Type listType = new TypeToken<ArrayList<clazz>>() {
is any way to use arraylist with anonymous class?