我想使用共享首选项来持久化数据。但它给了我一个错误,
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
和
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
我没有得到什么问题。 我的代码在这里,
public void setStoreType(List<StoreType> st) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(StoreType.class, new StoreType());
Gson gson = gsonBuilder.create();
JsonElement element = gson.toJsonTree(st, new TypeToken<List<StoreType>>() {
}.getType());
if (!element.isJsonObject()) {
} else {
pref = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
editor = pref.edit();
editor.putString("STORE_TYPE", element.getAsJsonObject()
.toString());
editor.commit();
}
}
public List<StoreType> getStoreType() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(StoreType.class, new StoreType());
Gson gson = new Gson();
pref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Type type = new TypeToken<List<StoreType>>() {
}.getType();
if (gson.fromJson(pref.getString("STORE_TYPE", "{}"), type) == "{}") {
return new ArrayList<StoreType>();
}
return gson.fromJson(pref.getString("STORE_TYPE", "{}"), type);
}
我想在其中设置arraylist。请告诉我这是什么问题。谢谢。