0

I have stored JSONArray as a String in SharedPreference.This is my JSONObject

JSONObject info = new JSONObject();
        try {
            info.put("name", full_name);
            info.put("phone", foodie_contact);                    
            info.put("no_people", no_peoples);
        } catch (JSONException e) {
            e.printStackTrace();
        }  

And I am storing this Object in Array and array in SharedPreference as

JSONArray array=new JSONArray();
            array.put(info.toString());
            alert.noInternetAlert(getActivity());
            edit=addqueuetemp.edit();
            edit.putString("queuedata",array.toString());
            edit.apply();  

Now, I am taking JSONArray from SharedPreference and parse it as

try {
                JSONArray array=new JSONArray(addqueuetemp.getString("queuedata","[]"));
                for(int i=0;i<array.length();i++){
                    JSONObject obj=array.getJSONObject(i+1);
                    Log.i("OBJECT",obj.toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }  

The format of String I am getting after reading from Preference is
["{\"name\":\"payal\",\"phone\":\"7427427427\",\"no_people\":\"5\"}"]
I am getting Error as
Value {"name":"payal","phone":"7427427427","no_people":"5"} at 0 of type java.lang.String cannot be converted to JSONObject
How to resolve this ? where is the actual problem ?

Satyam Gondhale
  • 1,415
  • 1
  • 16
  • 43
  • Use `Gson` to parse **string** to and from `JSON`. issue is direct parsing to **string from JSON** appends additional quotes. – Jeel Vankhede Oct 30 '18 at 06:04

3 Answers3

1

Try changing

array.put(info.toString());

to

array.put(info);

As you want to save object in array , but actually you're saving String in array

Ali Ahmed
  • 2,130
  • 1
  • 13
  • 19
1

You are putting a String into your JSONArray, not the JSONObject:

array.put(info.toString());

That's why you can only get it as a String.

Remove that .toString(), and it will work

Vladyslav Matviienko
  • 10,610
  • 4
  • 33
  • 52
0

To convert your string to json array you need to use follow code.

JsonParser jsonParser = new JsonParser();
JSONArray jo = (JSONArray)jsonParser.parse(json);
karan
  • 8,637
  • 3
  • 41
  • 78