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 ?

1
  • Use Gson to parse string to and from JSON. issue is direct parsing to string from JSON appends additional quotes. Commented Oct 30, 2018 at 6:04

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

JsonParser jsonParser = new JsonParser();
JSONArray jo = (JSONArray)jsonParser.parse(json);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.