预期BEGIN_ARRAY但在第1行第2列是BEGIN_OBJECT,jsonSyntax错误

时间:2016-09-28 08:53:05

标签: java android json hashset

我想将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;
    }
}

2 个答案:

答案 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