【问题标题】:Error trying to use GSON with own class尝试将 GSON 与自己的类一起使用时出错
【发布时间】:2016-04-20 20:49:45
【问题描述】:

我第一次尝试在我的 Android 应用中使用 Google 的 GSON。我想将 GSON 与一个名为 UserValues 的类一起使用,它将我的大部分 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_;
    ...

    }

【问题讨论】:

  • 该错误表明 UserValues (public UserValues () {}) 的默认构造函数不可访问。这是因为一个不存在,或者它被标记为私有。

标签: java android gson android-sharedpreferences


【解决方案1】:

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

public UserValues() {

}

【讨论】:

  • 我在 UserValues 类中删除上下文后,GSON 就可以正常工作了。谢谢!
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    在类定义中添加空构造函数

    public UserValues() {}
    

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-12
        • 2019-08-24
        相关资源
        最近更新 更多