【问题标题】:Error while Reading and Parsing JSONArray String from SharedPreference从 SharedPreference 读取和解析 JSONArray 字符串时出错
【发布时间】:2018-10-30 05:58:01
【问题描述】:

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

我将此对象存储在 Array 中,并将 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 中读取后得到的字符串格式为
["{\"name\":\"payal\",\"phone\":\"7427427427\",\"no_people\":\"5\"}"]
我收到错误为
Value {"name":"payal","phone":"7427427427","no_people":"5"} at 0 of type java.lang.String cannot be converted to JSONObject
如何解决这个问题?真正的问题在哪里?

【问题讨论】:

  • 使用 Gson 解析 string 到 JSON 和从 JSON 解析。问题是直接从 JSON 解析到 字符串 会附加额外的引号。

标签: android json sharedpreferences jsonexception


【解决方案1】:

您将String 放入您的JSONArray,而不是JSONObject:

array.put(info.toString());

这就是为什么您只能以String 的形式获取它。

删除.toString(),它将起作用

【讨论】:

    【解决方案2】:

    尝试改变

    array.put(info.toString());
    

    到

    array.put(info);
    

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

    【讨论】:

      【解决方案3】:

      要将您的字符串转换为 json 数组,您需要使用以下代码。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-14
        • 1970-01-01
        • 2017-07-17
        • 1970-01-01
        • 2014-10-31
        • 2017-09-26
        • 1970-01-01
        相关资源
        最近更新 更多