android - 从 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 ?实际问题在哪里?
解决方案
尝试改变
array.put(info.toString());
至
array.put(info);
因为您想将对象保存在数组中,但实际上您保存String
在数组中
推荐阅读
- c - 为什么指针与下一个内存位置有 12 个差异
- sql - 如何删除字符串中的数字但保留postgresql中的空格?
- maven - Maven 包含由该构建生成的 JAR
- android - Kotlin:从自身/内部引用匿名对象(通过this)
- amazon-cloudformation - 在嵌套的 cloudformation 堆栈中共享价值上游可能吗?
- python - 如何使装饰器对调试器透明
- javascript - 为什么 JSON.parse() 会在元素前面添加数字?
- biztalk - 您可以在 BizTalk 2006 中使用“HAT”查看邮件正文吗?
- python - Celery group.apply_async().join() 永远不会返回
- ionic-framework - 无法在 ionic 中添加 android 平台