0
votes

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;
}
1
Is the serialVersionUID field for satisfying Serializable? That field should be static and Gson doesn't deal with static fields. Please show your class hierarchy (the necessary parts of it to reproduce this error). - Sotirios Delimanolis
I have to serialise also static fields, so I add gsonBuilder.excludeFieldsWithModifiers(java.lang.reflect.Modifier.TRANSIENT);. Questions is updated. - Guneli

1 Answers

0
votes

After analysing GSON's source code, I was able to come up with the solution myself. To exclude field so that you do not get "class Person declares multiple JSON fields named serialVersionUID" error, you should also add deserialization exclusion strategy:

gsonBuilder.addDeserializationExclusionStrategy(excludePolicy);

So the final code is:

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.addDeserializationExclusionStrategy(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();
}