Gson: How to exclude specific fields from Serialization without annotations

后端 未结 15 1447
后悔当初
后悔当初 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:13

    I have Kotlin version

    @Retention(AnnotationRetention.RUNTIME)
    @Target(AnnotationTarget.FIELD)
    internal annotation class JsonSkip
    
    class SkipFieldsStrategy : ExclusionStrategy {
    
        override fun shouldSkipClass(clazz: Class<*>): Boolean {
            return false
        }
    
        override fun shouldSkipField(f: FieldAttributes): Boolean {
            return f.getAnnotation(JsonSkip::class.java) != null
        }
    }
    

    and how You can add this to Retrofit GSONConverterFactory:

    val gson = GsonBuilder()
                    .setExclusionStrategies(SkipFieldsStrategy())
                    //.serializeNulls()
                    //.setDateFormat(DateFormat.LONG)
                    //.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                    //.setPrettyPrinting()
                    //.registerTypeAdapter(Id.class, IdTypeAdapter())
                    .create()
            return GsonConverterFactory.create(gson)
    

提交回复
热议问题