I have to serialize Java classes without modifying their source code. I am using GSON and getting "class Person declares multiple JSON fields named serialVersionUID", as the superclass of Person also has this field. So I want to to exclude fields named serialVersionUID during serialisation to avoid this error (it is ok for my purposes) adding the code below:
GsonBuilder gsonBuilder = new GsonBuilder();
ExclusionStrategy excludePolicy = new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes arg0) {
return arg0.getName().contains("serialVersionUID");
}
@Override
public boolean shouldSkipClass(Class<?> arg0) {
return false;
}
};
gsonBuilder.addSerializationExclusionStrategy(excludePolicy);
gsonBuilder.excludeFieldsWithModifiers(java.lang.reflect.Modifier.TRANSIENT);
Gson gson = gsonBuilder.create();
Writer writer;
try {
writer = new FileWriter("fileLoc");
gson.toJson(personList, writer);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
However, I still get the error and cannot understand the reason beyond it.
Here is the example class hierarchy:
public class Person extends SuperPerson {
private static final long serialVersionUID = 1L;
}
public class SuperPerson {
private static final long serialVersionUID = 1L;
}