Gson: How to exclude specific fields from Serialization without annotations

后端 未结 15 1443
后悔当初
后悔当初 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条回答
  •  -上瘾入骨i
    2020-11-22 06:06

    I solved this problem with custom annotations. This is my "SkipSerialisation" Annotation class:

    @Target (ElementType.FIELD)
    public @interface SkipSerialisation {
    
    }
    

    and this is my GsonBuilder:

    gsonBuilder.addSerializationExclusionStrategy(new ExclusionStrategy() {
    
      @Override public boolean shouldSkipField (FieldAttributes f) {
    
        return f.getAnnotation(SkipSerialisation.class) != null;
    
      }
    
      @Override public boolean shouldSkipClass (Class clazz) {
    
        return false;
      }
    });
    

    Example :

    public class User implements Serializable {
    
      public String firstName;
    
      public String lastName;
    
      @SkipSerialisation
      public String email;
    }
    

提交回复
热议问题