Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make gson exclude my object's superclass?

Tags:

java

gson

Im trying to serialize/deserialize using Gson. I don't want the super class (which is abstract) to be considered, the problem is that I don't have access to the super class code.

I've tried with an ExclusionStrategy but it 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 the fields in the superclass to be ignored, this is because I am getting this error: MyClass declares multiple JSON fields named. I can not change the conflicting fields name.

Solution:

Solved with the following strategy:

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");
  }
 }
like image 651
Federico Perez Avatar asked Mar 31 '14 14:03

Federico Perez


People also ask

Does Gson ignore extra fields?

As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.

Does Gson ignore transient fields?

By default, GSON excludes transient and static fields from the serialization/deserialization process.

How would you exclude a field of a class from serialization?

If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.


1 Answers

From the Gson documentation

Exclude fields and objects based on a particular 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()());
   }
}
like image 76
René Link Avatar answered Sep 28 '22 02:09

René Link