I'm trying to convert a complex Java object into JSON. But I'm not able to do so. I am using Java generics.
This the generic object to store page output. I am not posting JsonTest Object structure. it is same as any normal java class with property and setter and getter.
class ListRow<T>{
private int total;
private int currentRow;
private List<T> test;
public ListRow(int total, int currentRow, List<T> test) {
this.total = total;
this.currentRow = currentRow;
this.test = test;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getCurrentRow() {
return currentRow;
}
public void setCurrentRow(int currentRow) {
this.currentRow = currentRow;
}
public List<T> getTest() {
return test;
}
public void setTest(List<T> test) {
this.test = test;
}
JsonTest test = new JsonTest("naveen", 20, 20000);
JsonTest test2 = new JsonTest("parveen", 20, 20000);
JsonTest test3 = new JsonTest("pawan", 20, 20000);
JsonTest test4 = new JsonTest("anil", 20, 20000);
List<JsonTest> list = new ArrayList<JsonTest>();
list.add(test);
list.add(test2);
list.add(test3);
list.add(test4);
Gson gson = new Gson();
System.out.print(gson.toJson(list));
When I run this program with this values, I got the correct output:
[{"name":"naveen","age":20,"salary":20000.0},{"name":"parveen","age":20,"salary":20000.0},{"name":"pawan","age":20,"salary":20000.0},{"name":"anil","age":20,"salary":20000.0}]
But when I write the following code to achieve generic feature of Java, I do not get the desired output:
Gson gson = new Gson();
ListRow<JsonTest> dataList = new ListRow<JsonTest>(2, 2, list);
System.out.print(gson.toJson(dataList));
Output is:
{"total":2,"currentRow":2,"test":[{},{},{},{}]}.
What's wrong with this code? How can I get the desired output? I want to work with generic feature since I want to write code once for Grid and then pass any object to display in grid.
Json Test case:
public static void main(String[] args) {
JsonTest test = new JsonTest("naveen", 20, 20000);
JsonTest test2 = new JsonTest("parveen", 20, 20000);
JsonTest test3 = new JsonTest("pawan", 20, 20000);
JsonTest test4 = new JsonTest("anil", 20, 20000);
List<JsonTest> list = new ArrayList<JsonTest>();
list.add(test);
list.add(test2);
list.add(test3);
list.add(test4);
Gson gson = new Gson();
System.out.print(gson.toJson(list));
ListRow<JsonTest> dataList = new ListRow<JsonTest>(2, 2, list);
System.out.print(gson.toJson(dataList));
}
JsonTest? please post it