我有这样的课程项目
class Item {
private String name;
private int age;
private boolean gender;
}
和一个包含此Item类的类ListItem {private List items; }
当使用gson生成JSON时,它将返回类似这样的内容
[{"name": "a", "age": "a1", "gender": "male"}, {"name": "b", "age": "b1", "gender": "female"}, ...]
但我想自定义(不改变POJO类,因为我不能这样做)和方法
List listItems = new ArrayList();
listItems.add(new Item("a", "a1", "male");
listItems.add(new Item("b", "b1", "female");
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(listItems);
那么jsonElement会在JSON字符串中生成一个这样的结构(对象列表和“name”:“object”)
{
"a": { "name": a, "age": "a1", "gender": "male" },
"b": { "name": b, "age": "b1", "gender": "female"}
}
当我序列化它
String json = gson.toJson(jsonElement);