Nitin Thakor
Nitin Thakor

Reputation: 535

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2, jsonSyntax Error

I want to save Hashset Object in to Sharedpreference and than want retrieve that data. I am storing data in to hashset and and converting object in to json using Gson. Actually m storing bitmap in to Hashset. I am able to convert and save Hashsetobject into sharedpreference. I am getting problem when I am retrieving and converting json to Hashset Object.

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

Here is Method For Saving Object in to 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();

}

Method For Retrieving That Object.

   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;
    }
}

Upvotes: 0

Views: 141

Answers (2)

Benny Huo
Benny Huo

Reputation: 430

You serialise a object and want to deserialise it into a HashSet. That's the problem.

Object spSquare = c.getStringDrawObjImages();

What's the type of spSquare? Suppose it is 'Foo.class', you should deserialise it like this:

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

'foo.img' should be your HashSet

Upvotes: 1

Nikhil
Nikhil

Reputation: 3711

As per your comment your json as follows is not in format so that Gson can parse it as you are receiving your circle attribute in string not as 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,]‌​]"
}

So your Json is received as object having only attribute that is img.

and you are parsing it as array. That's error. So contact your back end developer and change json structure accordingly.

Upvotes: 1

Related Questions