Error trying to use GSON with own class

霸气de小男生 提交于 2019-12-11 05:42:06

问题


I'm trying to use Google's GSON for the first time in my Android app. I want to use GSON with a class called UserValues, which keeps most of my ArrayList, booleans, Strings and other basic objects in one place. My goal is to save an instance of UserValues into SharedPreferences. I wrote:

Gson gson = new Gson();
        String userValuesJSON=gson.toJson(userValues);
        getSharedPreferences(myAppKey, MODE_PRIVATE).edit().putString("JSON", userValuesJSON).commit();

The error I get:

java.lang.SecurityException: Can't make method constructor accessible
            at java.lang.reflect.Constructor.setAccessible(Constructor.java:336)
            at com.google.gson.internal.ConstructorConstructor.newDefaultConstructor(ConstructorConstructor.java:97)
            at com.google.gson.internal.ConstructorConstructor.get(ConstructorConstructor.java:79)
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:71)
            at com.google.gson.Gson.getAdapter(Gson.java:356)

when I added GSON I added the following to build.gradle:

repositories {
    mavenCentral()
}

dependencies {   
    compile 'com.google.code.gson:gson:2.2.4'
}

Any brainstorming greatly appreciated!

EDIT: This is how the constructor looks like:

public class UserValues implements Serializable {

    private Integer period;
    private Float fee;
    private ArrayList<Boolean> theBooleans = new ArrayList<>();
    private ArrayList<Integer> theIntegers = new ArrayList<>();
    private static final ArrayList<String> theIntegerKeys = new ArrayList<>();
    private static final ArrayList<String> theBooleanKeys = new ArrayList<>();
    public static final String myAppKey = "Investor Playground";
    private static final ArrayList<Integer> theIntDefValues = new ArrayList<>();
    private ArrayList<Float> arrayList;
    private ArrayList<ArrayList<Integer>> theDates;
    private ArrayList<Float> strategyResult;
    private int theCurrentFragment;

    private int theCurrentGraph;

    Context context;


    public UserValues(Context context_) {
        context=context_;
    ...

    }

回答1:


add an empty constructor to the class as this will only be used to set values this should not cause any issues if the context is not initialised

public UserValues() {

}



回答2:


Your UsersValues class must have a public empty parameter constructor to be used with gson.




回答3:


Add empty constructor to your class definition

public UserValues() {}

also you can't have Context as a variable if you want to use Gson



来源:https://stackoverflow.com/questions/36754923/error-trying-to-use-gson-with-own-class

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