1
votes

I have class A, that extends class B, that implements Serializable.

When i try to transform it in a JSON, using GSON lib, it says that "class declares multiple JSON fields named serialVersionUid".

As long as i know, if i don't explicit declare serialVersionUid, it is generated by GSON.

I also tried to put serialVersionUid statically, but doesn't work.

I can fix the error by implementing Serialization in class A, but i have many classes that extends B, and i don't think exclude B from them will be a good ideia...

Does anyone know why this error occurs?

Class A extends B {
    private c;
    private d;
    private e;
}

Class B extends Serializable{
    private f;
    private g;
}
1
@RC. This question is similar, but that's not my problem. My problem is that the field being declared multiple IS NOT declared by me, it its generated automatically. The related question is about fields i create by myself. - Geovane Jocksch
A class can't extend Serializable. What's the real code? - user207421

1 Answers

4
votes

EDITED:

We've changed the code there to use GSON with a customised GsonBuilder class. The code is looking a little bit like that:

...
private static final List<String> EXCLUDE = new ArrayList<String>() {{
    add("serialVersionUID");
    add("CREATOR");
}};
....
Gson gson = new GsonBuilder()
            .excludeFieldsWithModifiers(Modifier.TRANSIENT)
            .setExclusionStrategies(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes f) {
                    boolean exclude = false;
                    try {
                        exclude = EXCLUDE.contains(f.getName());
                    } catch (Exception ignore) {
                    }
                    return exclude;
                }

                @Override
                public boolean shouldSkipClass(Class<?> clazz) {
                    return false;
                }
            })
            .create();
return gson.toJson(object);

In this case, we're ignoring the serialVersionUID and the CREATOR fields when jsonizing it.

OLD:

I had the same issue some seconds ago. I've solved it by adding serialVersionUUID using the transient modifier. to by superclass, like that:

private transient static final long serialVersionUID = 1L;

I hope it helps you too.