文章目录
一.简单的gson使用
1 string to json
Gson gson = new Gson();
String jsonMes ="{\"id\":1,\"name\":\"李四\",\"birthDay\":\"Mar 24, 2019 1:11:36 PM\"}";
Student student1 = gson.fromJson(jsonMes, Student.class);
2 json to string
Student student = new Student();
student.setBirthDay(new Date());
student.setId(1);
student.setName("李四");
Gson gson = new Gson();
String s = gson.toJson(student);
3 arraylist to json
Student one = new Student("one");
Student two = new Student("two");
ArrayList<Student> students = new ArrayList<>();
students.add(one);
students.add(two);
Gson gson = new Gson();
String s = gson.toJson(students);
System.out.println(s);
4 json to arrylist
String jsonList ="[{\"id\":0,\"name\":\"one\"},{\"id\":0,\"name\":\"two\"}]";
Gson gson = new Gson();
/*
ArrayList arrayList = gson.fromJson(jsonList, ArrayList.class);
// that is wrong ,gson不知道如何解析,给什么对象赋值
Student o = (Student)arrayList.get(0);
*/
ArrayList<Student> arrayList = gson.fromJson(jsonList, new TypeToken<List<Student>>() {
}.getType());
Student student = arrayList.get(0);
System.out.println(student.getName());
二. Gson 的注解
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation() //没有用@Expose注解的属性无法导出
.enableComplexMapKeySerialization() //支持Map的key为复杂对象的形式
.serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")//时间转化为特定格式
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)//会把字段首字母大写,注:对于实体上使用了@SerializedName注解的不会生效.
.setPrettyPrinting() //对json结果格式化.
.setVersion(1.0) //有的字段不是一开始就有的,会随着版本的升级添加进来,那么在进行序列化和返序列化的时候就会根据版本号来选择是否要序列化.
//@Since(版本号)能完美地实现这个功能.还的字段可能,随着版本的升级而删除,那么
//@Until(版本号)也能实现这个功能,GsonBuilder.setVersion(double)方法需要调用.
.create();
public class Student {
private int id;
@Expose
private String name;
@Expose(serialize = true, deserialize = false)
@SerializedName("bir")
//起别名,我记得之前学习的时候可以起多个别名的
// 像这样会报错 @SerializedName(value = "birthDay",alternate = {"birthDay","birthDay1","birthDay2"})
// 请谁清楚可以告知一下
private Date birthDay;
@SerializedName(value = "orderDetail",alternate = {"orderDetail1","advert"})
private int sex;
}
三. gson 的过滤
1. @Expose
利用注解,有@Expose才可以输出.
2. 利用属性名和类型进行过滤 方法:addSerializationExclusionStrategy
public void test() throws IOException {
Gson gson = new GsonBuilder()
.addSerializationExclusionStrategy(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes arg0) {
if (arg0.getName().equals("field4")) { //利用属性名
return true;
}
return false;
}
@Override
public boolean shouldSkipClass(Class<?> arg0) { //利用类型
return false;
}
}).create();
System.out.println(gson.toJson(new GsonObject()));
}
3.使用transient关键字
public class Student {
public transient boolean isLOLPlayer;
}
使用transient关键字,不适用builder 也可以实现过滤
4.通过修饰符
GsonBuilder 提供了excludeFieldsWithModifiers(int… modifiers)来排除特定修饰符的字段
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.PROTECTED)
.create();
写到一半,发现有些gson的过滤已经遗忘不会,一百度发现 pngfi已经总结的很好了,感谢 pngfi的分享.