2016-09-28 167 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

相關問題