1

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
    related: https://stackoverflow.com/questions/16476513/class-a-declares-multiple-json-fields –  Jul 07 '17 at 14:51
  • @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 Aug 07 '17 at 19:54
  • A class can't `extend Serializable`. What's the real code? – user207421 Aug 27 '17 at 01:36

1 Answers1

4

EDITED

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

...
private static final Set<String> EXCLUDED_FIELDS = Set.of("serialVersionUID", "CREATOR");
....
Gson gson = new GsonBuilder()
            .excludeFieldsWithModifiers(Modifier.TRANSIENT)
            .setExclusionStrategies(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes f) {
                    boolean exclude = false;
                    try {
                        exclude = EXCLUDED_FIELDS .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.

Denis Raison
  • 41
  • 1
  • 1
  • 6
  • Very strange. `transient` does nothing in association with `static`. Does it really have to be `transient`? – user207421 Aug 27 '17 at 01:52
  • 2
    The transient keyword in Java is used to indicate that a field should not be serialized. From the Java Language Specification, Java SE 7 Edition, Section 8.3.1.3. transient Fields: Variables may be marked transient to indicate that they are not part of the persistent state of an object. – Denis Raison Aug 27 '17 at 04:02