Gson的使用-2

2018-11-28  本文已影响0人  胖胖胖胖胖胖胖胖胖

Gson序列化空值

Gson在序列化的null值的时候,会自动忽略掉该字段,如果我们不想将其忽略,可以作如下设置;

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.serialiNulls();
Gson gson = gsonBuilder.create();

Gson 忽略字段 @Expose(serialized = true,deserialized =fale)必须设置其值

//@Expose将会忽略字段序列化和反序列化过程
public class User {
    @Expose()
    private int age;
    @Expose(serialize = true,deserialize = true)
    private String name;
    @Expose(serialize = true,deserialize = false)
    private String pw;
}


//必须设置excludeFieldsWithOutExposeAnnitation()才能起作用;
GsonBuilder builder = new GsonBuilder();  
builder.excludeFieldsWithoutExposeAnnotation();  
Gson gson = builder.create();  

使用Transient也可以实现忽略序列化,和反序列化

public class User{
 transient String name;
}

使用@Expose()和transient可以改变忽略单个字段的序列化和反序列化过程,我们还可以使用GsonBuilder来实现整体的配置;

setExclusionStrategies(new ExclusionStrategy())

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setExculsiongStrategies(new new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes f) {
                return f.getName().contains("-");
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
                return clazz == Boolean.class || clazz == int.class;
            }
        })
//其中shouldSkipField用来忽略单一类型的Field,shouldSkipClass 可以设置多个Type的类型;

注意:setExclusionStrategies()将生效序列化和反序列化,
还有addSerializationExclusionStrategy()
addDeserializationExclusionStrategy()可以单独设置序列化和反序列化是的忽略的内容;

excludeFieldsWithModifiers(Modifier.STATIC, Modifier.FINAL)


public class UserModifier {  
    private String name;
    private transient String email;
    private static boolean isDeveloper;
    private final int age;
}


上一篇下一篇

猜你喜欢

热点阅读