Why Exclusion Strategy by name does not prevent “class declares multiple JSON fields named XXX” error?

2181 views
Skip to first unread message

Cahangirova Gunel

unread,
Oct 14, 2017, 1:32:39 AM10/14/17
to google-gson

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;
}

vypro...@gmail.com

unread,
Jul 23, 2018, 1:51:54 PM7/23/18
to google-gson
I know this question is very old but I had the same issue and I found a workaround and I want to share it: just make transient serialVersionUID fields.

This is not the way of solving it for any other field, but serialVersionUID is a kind of special field as explained in Javadoc for Serializable interface: https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html
I'm sure any other field should be serialized by a JsonAdapter.

Inderjeet Singh

unread,
Jul 23, 2018, 1:55:53 PM7/23/18
to google-gson
Something is wrong in the way you have setup your Gson instance. 
serialVersionID is a static field, and Gson ignores them.

Please submit a PR to the Gson project with a JUnit test that reproduces the problem, and we can take a look.
Reply all
Reply to author
Forward
0 new messages