我希望将Hashset对象保存到Sharedpreference中,然后检索该数据。我将数据存储到hashset中,并使用Gson将对象转换为json。实际上我将位图存储到Hashset中。我能够将Hashsetobject转换并保存为sharedpreference。在检索json并将其转换为Hashset对象时遇到问题。
HashSet<images> img = new HashSet<images>(CIRCLES_LIMIT);下面是将Object保存到Sharedpreference中的方法。
public void saveString() throws JSONException {
Object spSquare = c.getStringDrawObjImages();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String jsonSquare = gson.toJson(spSquare)
editor.putString("kEySquare", jsonSquare);
editor.commit();
}方法来检索该对象。
public void openString() {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());
Gson gson = new Gson();
String jsonSquare=sharedPrefs.getString("kEySquare",null);
Type typeSquare = new TypeToken<HashSet<images>>(){}.getType();
HashSet<images> arrayListSquare = gson.fromJson(jsonSquare,typeSquare);`//getting Exception here jsonSyntax Error`
if (arrayListSquare != null) {
img = arrayListSquare;
}
}发布于 2016-09-28 17:03:28
根据您的注释,您的json如下所示的格式不正确,因此Gson可以在您收到string中的circle属性时对其进行解析,而不是作为json。
{
"img": "[Circle[218.69626, 475.58936, 0,android.graphics.Bitmap@42e13c70,0.0,0.0,0.0,0.0,0.0,0.0,], Circle[186.74065, 670.43713, 0,android.graphics.Bitmap@42e13c70,0.0,0.0,0.0,0.0,0.0,0.0,]]"
}因此,您的Json将作为仅具有img属性的对象接收。
并且您正在将其解析为数组。这是个错误。因此,请联系您的后端开发人员并相应地更改json结构。
发布于 2016-09-28 17:08:22
您序列化了一个对象,并希望将其反序列化为HashSet。这就是问题所在。
Object spSquare = c.getStringDrawObjImages();spSquare的类型是什么?假设它是'Foo.class',你应该像这样反序列化它:
Foo foo = gson.fromJson(jsonString, Foo.class);'foo.img‘应该是你的HashSet
https://stackoverflow.com/questions/39742495
复制相似问题