Gson: How to exclude specific fields from Serialization without annotations

后端 未结 15 1430
后悔当初
后悔当初 2020-11-22 05:39

I\'m trying to learn Gson and I\'m struggling with field exclusion. Here are my classes

public class Student {    
  private Long                id;
  privat         


        
15条回答
  •  既然无缘
    2020-11-22 06:21

    After reading all available answers I found out, that most flexible, in my case, was to use custom @Exclude annotation. So, I implemented simple strategy for this (I didn't want to mark all fields using @Expose nor I wanted to use transient which conflicted with in app Serializable serialization) :

    Annotation:

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    public @interface Exclude {
    }
    

    Strategy:

    public class AnnotationExclusionStrategy implements ExclusionStrategy {
    
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getAnnotation(Exclude.class) != null;
        }
    
        @Override
        public boolean shouldSkipClass(Class clazz) {
            return false;
        }
    }
    

    Usage:

    new GsonBuilder().setExclusionStrategies(new AnnotationExclusionStrategy()).create();
    

提交回复
热议问题