首页 > 解决方案 > 从 SharedPreference 读取和解析 JSONArray 字符串时出错

问题描述

我已经存储JSONArray为字符串。SharedPreference这是我的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();
        }  

我将此对象存储在数组中,并将数组存储在 SharedPreference 中

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

现在,我从 SharedPreference 中获取 JSONArray 并将其解析为

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

从 Preference 读取后得到的 String 格式是
["{\"name\":\"payal\",\"phone\":\"7427427427\",\"no_people\":\"5\"}"]
我收到 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 ?实际问题在哪里?

标签: androidjsonsharedpreferencesjsonexception

解决方案


尝试改变

array.put(info.toString());

array.put(info);

因为您想将对象保存在数组中,但实际上您保存String在数组中


推荐阅读