I have a class Item like this
class Item {
private String name;
private int age;
private boolean gender;
}
and a class which contains this Item class ListItem { private List items; }
When using gson to generate to JSON, it will return something like this
[{"name": "a", "age": "a1", "gender": "male"}, {"name": "b", "age": "b1", "gender": "female"}, ...]
but I want to customize (without changing the POJO class as I could not do this) and in method
List<Item> listItems = new ArrayList<Item>();
listItems.add(new Item("a", "a1", "male");
listItems.add(new Item("b", "b1", "female");
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(listItems);
then jsonElement will generate in to JSON string a structure like this (list of objects and with "name": "object")
{
"a": { "name": a, "age": "a1", "gender": "male" },
"b": { "name": b, "age": "b1", "gender": "female"}
}
when I serialize it
String json = gson.toJson(jsonElement);