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

Error trying to use GSON with own class

我第一次尝试在我的 Android 应用程序中使用 Google 的 GSON。我想将 GSON 与一个名为 UserValues 的 class 一起使用,它将我的大部分 ArrayList、布尔值、字符串和其他基本对象保存在一个地方。我的目标是将 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_;
    ...

    }

你的 UsersValues class 必须有一个 public 空参数构造函数才能与 gson 一起使用。

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

public UserValues() {

}

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

public UserValues() {}

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

这个话题已经过了很长时间了,但是对于其他人我来说说。 如果您的模型中有 View class! Gson 无法将其转换为 json 并抛出 java.lang.SecurityException: Can't make method constructor accessible...

我通过从我的模型中删除视图字段解决了我的问题。