How can I make gson exclude my class superclass?

I am trying to serialize / deserialize using Gson. I don't want to consider a superclass (which is abstract), the problem is that I don't have access to the superclass of the class.

I tried with ExclusionStrategybut that didn't work.

private class SuperClassExclusionStrategy implements ExclusionStrategy {

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return clazz.equals(SuperClass.class);
        }

        @Override
        public boolean shouldSkipField(FieldAttributes field) {
            return false;
        }

    }

How can i solve this?

Edit:

I need to get the field in the superclass ignored because I get this error: MyClass declares multiple JSON fields named. I cannot change the name of the conflicting fields.

Decision:

The following strategy has been resolved:

private static class SuperClassExclusionStrategy implements ExclusionStrategy {

  public boolean shouldSkipClass(Class<?> clazz) {
   return false;
  }

  public boolean shouldSkipField(FieldAttributes field) {
   return field.getDeclaringClass().equals(MySuperClass.class) && field.getName()
    .equals("id");
  }
 }
+4
source share
1 answer

From the Gson documentation

Exclude fields and objects based on a specific class type:

private static class SpecificClassExclusionStrategy implements ExclusionStrategy {
    private final Class<?> excludedThisClass;

    public SpecificClassExclusionStrategy(Class<?> excludedThisClass) {
        this.excludedThisClass = excludedThisClass;
    }

    public boolean shouldSkipClass(Class<?> clazz) {
        return excludedThisClass.equals(clazz);
   }

   public boolean shouldSkipField(FieldAttributes f) {
        return excludedThisClass.equals(f.getDeclaringClass()());
   }
}
+6
source

Source: https://habr.com/ru/post/1534266/


All Articles