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");
}
}
As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.
By default, GSON excludes transient and static fields from the serialization/deserialization process.
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.
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()());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With