gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:46:59 25 4
gpt4 key购买 nike

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

非常感谢任何头脑 Storm !

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

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

}

最佳答案

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

public UserValues() {

}

关于java - 尝试将 GSON 与自己的类一起使用时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36754923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com