此文仅作为笔记,部分参考于:
1.http://www.jianshu.com/p/0e40a52c0063
2.《第一行代码》
类
json:{"name": "TOM", "age": "20"}
json -> 类:
Gson gson = ne Gson();
Person person = gson.from(jsonString, Person.Class)
类 -> json
Gson gson = ne Gson();
Person man = new Person();
String json = gson.toJson(man);
数组
json:[{"name": "TOM", "age": "20"}, {"name": "SG", "age": "21"}]
json -> 类:
Gson gson = ne Gson();
Type type = new TypeToken<List<Person>>(){}.getType();
Person person = gson.from(jsonString, type)
类 -> json
Gson gson = ne Gson();
Type type = new TypeToken<List<Person>>(){}.getType();
List<Person> personList;
String json = gson.toJson(personList, type);
增加注解,避免循环引用
public class Category {
public int id;
public String name;
public List<Category> children;
//因业务需要增加,但并不需要序列化
public Category parent;
}
category中有category,由于业务需要子category需要父的引用。会导致gson序列化和反序列化发生死循环,需要过滤parent。
public class Category {
@Expose public int id;
@Expose public String name;
@Expose public List<Category> children;
//不需要序列化,所以不加 @Expose 注解,
//等价于 @Expose(deserialize = false,serialize = false)
public Category parent;
}
//不可简单的使用new Gson(),而要使用GsonBuilder
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();