我想将Hashset
对象保存到Sharedpreference
,而不想要检索该数据。我将数据存储到hashset
,并使用json
将对象转换为Gson
。实际上是将位图存储到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;
}
}
答案 0 :(得分:1)
根据您的评论,您的json
格式不正确,以便Gson
可以在string
中收到您的圈子属性而不是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
结构。
答案 1 :(得分:1)
您序列化对象并希望将其反序列化为HashSet。这就是问题所在。
Public Function GETSHEETNAME(address As String, Optional SheetNumber As Integer = 1) As String
Set WS = GetObject(address).Worksheets
GETSHEETNAME = WS(SheetNumber).Name
End Function
spSquare的类型是什么?假设它是&#39; Foo.class&#39;,你应该像这样反序列化它:
Object spSquare = c.getStringDrawObjImages();
&#39; foo.img&#39;应该是你的HashSet