Object of class containing AtomicInteger's fails to be converted to JSON using GSON

為{幸葍}努か 提交于 2019-12-25 04:07:20

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/40243712/object-of-class-containing-atomicintegers-fails-to-be-converted-to-json-using-g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!