conversion between list of objects and Gson string
I'm converting a list of objects to json string and then back to list of
objects as below:
List<Work> list = new ArrayList<Work>();
Work w1 = new Work();
Work w2 = new Work();
list.add(w1);
list.add(w2);
String str = GsonUtils.getJsonString(list);
Type listType = new TypeToken<ArrayList<Work>>() {
}.getType();
List<Work> list1 = new Gson().fromJson(str, listType);
this works completely fine and returns the list List<Work>.
Now I'm doing same by extracting a method as below:
List<Work> list = new ArrayList<Work>();
Work w1 = new Work();
Work w2 = new Work();
list.add(w1);
list.add(w2);
String str = GsonUtils.getJsonString(list);
Type listType = new TypeToken<ArrayList<Work>>() {
}.getType();
List<Work> list1 = getListFromJSON(str, Work.class);
where method is defined as below:
public <T> List<T> getListFromJSON(String str, Class<T> type) {
Type listType = new TypeToken<ArrayList<T>>() {
}.getType();
List<T> list = new Gson().fromJson(str, listType);
return list;
}
this time it's resulting into an error:
Exception in thread "main" java.lang.ClassCastException:
com.google.gson.internal.StringMap cannot be cast to
com.restfb.types.User$Work
at expt.ExptGsonList.main(ExptGsonList.java:45)
Please help me to know where am I going wrong and how can I get this
working using method?
No comments:
Post a Comment