0

I am trying to serialize an Object of Class (let's say MyClass)

Here is roughly how MyClass.java looks like:

public class MyClass {

    private static final AtomicInteger variableOne = new AtomicInteger();
    private static final AtomicInteger variableTwo = new AtomicInteger();
    private static final AtomicInteger variableThree = new AtomicInteger();
    private static final AtomicInteger variableFour = new AtomicInteger();


    /*
    * Have the getters and setters here
    */
}

I am trying to convert object of the above class to JSON using GSON

Here is the code:

GsonBuilder gsonBuilder  = new GsonBuilder();
gsonBuilder.excludeFieldsWithModifiers(java.lang.reflect.Modifier.TRANSIENT);
Gson gson = gsonBuilder.create();
String jsonObject = gson.toJson(new MyClass());

But it throws the following exception:

class java.util.concurrent.atomic.AtomicInteger declares multiple JSON fields named serialVersionUID

I am not sure how to deal with this issue as most of the answers on S.O and other forums ask to make the variable TRANSIENT and that's basically not the idea of what I want to achieve.

Nick Div
  • 5,338
  • 12
  • 65
  • 127

1 Answers1

0

For anyone who would come across such a problem, I found an answer:

Register your GsonBuilder with the FieldExcluder (I have named it FieldExtractor)

GsonBuilder gsonBuilder = new GsonBuilder().setExclusionStrategies(new FieldExtractor()); 

The FieldExcluder will look something like:

 private class FieldExtractor implements ExclusionStrategy {

            @Override
            public boolean shouldSkipClass(Class<?> arg0) {
                return false;
            }

            @Override
            public boolean shouldSkipField(FieldAttributes f) {

                if ("serialVersionUID".equals(f.getName())) {
                    return true;
                }

                return false;
            }

        }

Basically you can ignore any field that gives you exception in the format of:

declares multiple JSON fields named serialVersionUID

You can further modify the if condition to further suit your requirement.

Nick Div
  • 5,338
  • 12
  • 65
  • 127