Gson序列化时排除字段的几种方式

阅读更多

 

 

1、使用@Expose注解

class Hello {
    
    public int x;
    @Expose 
    public int y;
    
    public Hello(int x, int y) {
        this.x = x;
        this.y = y;
    }
    
}

 

 Gson gson = new GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .create();

 

2、使用Modifier排除指定类型的字段

import java.lang.reflect.Modifier;
Gson gson = new GsonBuilder()
                .excludeFieldsWithModifiers(Modifier.PROTECTED) 
                .create();

 

3、ExclusionStrategy定制字段排除策略

ExclusionStrategy myExclusionStrategy = new ExclusionStrategy() {
 
            @Override
            public boolean shouldSkipField(FieldAttributes attr) {
                return "arrayList".equals(attr.getName()); 
            }
 
            @Override
            public boolean shouldSkipClass(Class clazz) {
                return false;
            }
            
        };
        
        Gson gson = new GsonBuilder()
                .setExclusionStrategies(myExclusionStrategy)
                .create();

 

你可能感兴趣的:(Gson序列化时排除字段的几种方式)