2016-09-28 319 views
0

我想保存​​对象到Sharedpreference并比想要检索该数据。我将数据存储到hashset,并使用Gson将对象转换为json。其实m存储位图到​​。我能够将Hashsetobject转换并保存到sharedpreference。当我检索并将json转换为​​对象时,我遇到了问题。预计BEGIN_ARRAY,但是在BEGIN_OBJECT在第1行第2列,jsonSyntax错误

HashSet<images> img = new HashSet<images>(CIRCLES_LIMIT); 

这里是法中Sharedpreference保存Object

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

分享您的JSON – Nikhil

+0

{ \t “IMG”:“[圈[ 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,]]“ } –

回答

1

根据您的评论你的json如下不是格式,以便为您在string收到您的圈子属性不是jsonGson可以解析它。

{ 
    "img": "[Circle[218.69626, 475.58936, 0,[email protected],0.0,0.0,0.0,0.0,0.0,0.0,]‌​, Circle[186.74065, 670.43713, 0,[email protected],0.0,0.0,0.0,0.0,0.0,0.0,]‌​]" 
} 

所以你Json被接收为仅具有对象属性是img

并且您将它解析为数组。这是错误的。因此请联系您的后端开发人员并相应地更改json结构。

+0

其实我已经检查json在jsonlint.com和它显示有效json –

+0

@NitinMakwana它是有效的json,但无效解析为数组通过Gson – Nikhil

+0

是否有可能转换位映射到json? –

1

您将一个对象序列化并想将其反序列化为一个HashSet。那就是问题所在。

Object spSquare = c.getStringDrawObjImages(); 

什么是spSquare的类型?假设它是 '让Foo.class',你应该deserialise这样的:

Foo foo = gson.fromJson(jsonString, Foo.class); 

'foo.img' 应该是你的HashSet

+0

它不工作.. –

+0

你应该找出正确的类。什么是spSquare的类型?它似乎只有一个字段是'img',字段'img'是你的HashSet,不是吗? – Bennyhuo

相关问题