尝试将GSON与自己的类一起使用时出错

时间:2016-04-20 20:49:45

标签: java android gson android-sharedpreferences

我正试图在我的Android应用中首次使用Google的GSON。我想将GSON与一个名为UserValues的类一起使用,它将我的大多数ArrayList,booleans,Strings和其他基本对象保存在一个地方。我的目标是将UserValues的实例保存到SharedPreferences。我写道:

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

我得到的错误:

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)

当我添加GSON时,我将以下内容添加到build.gradle

repositories {
    mavenCentral()
}

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

任何头脑风暴都非常感激!

编辑:这是构造函数的样子:

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_;
    ...

    }

4 个答案:

答案 0 :(得分:1)

您的UsersValues类必须有一个公共空参数构造函数才能与gson一起使用。

答案 1 :(得分:1)

在类中添加一个空构造函数 因为这只会用于设置值,如果上下文未初始化,这不会导致任何问题

{{1}}

答案 2 :(得分:0)

将空的构造函数添加到您的类定义中

public UserValues() {}

如果您想使用Gson,也不能将Context作为变量

答案 3 :(得分:0)

这个主题已经讨论了很长时间了,但是对于其他人,我要说。 如果您的模型中有View类! Gson无法将其转换为json并抛出 java.lang.SecurityException:无法使方法构造函数可访问 ....

我通过从模型中删除“视图”来解决问题。