【发布时间】:2016-10-30 06:12:14
【问题描述】:
我正在从 Parse 中检索 ParseObject 列表并将其转换为 HashMap 列表,然后将其转换为 JSONArray 并作为字符串存储在 SharedPrefrences 中
List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < list.size(); i++) {
ParseObject foundObject = list.get(i);
HashMap<String, Object> industry = new HashMap<String, Object>();
industry.put("CategoryName", foundObject.get("category"));
industry.put("lastUpdated", new Date());
industry.put("Jobs", foundObject.getList("jobs"));
data.add(industry);
}
JSONArray result = new JSONArray(data);
editor.putString("Categories", result.toString());
editor.commit();
然后我从本地保存的 String(JSONArray) 中检索
String storedCollection = pref.getString("Categories", null);
//Parse the string to populate your collection.
collection = new ArrayList<HashMap<String, Object>>();
if (storedCollection != null) {
try {
JSONArray array = new JSONArray(storedCollection);
HashMap<String, Object> item = null;
for (int i = 0; i < array.length(); i++) {
try {
JSONObject obj = new JSONObject((String) array.get(i));
Iterator<String> it = obj.keys();
item = new HashMap<String, Object>();
while (it.hasNext()) {
String key = it.next();
item.put(key, obj.get(key));
}
if (item == null) {
JSONObject obj2 = (JSONObject) array.get(i);
Iterator<String> it1 = obj2.keys();
item = new HashMap<String, Object>();
while (it1.hasNext()) {
String key = it.next();
item.put(key, obj2.get(key));
}
}
} catch (JSONException e) {
}
collection.add(item);
}
} catch (JSONException e) {
Log.e("JSON", "while parsing", e);
}
}
在棒棒糖版本及以上版本上运行良好,但在较低版本上会出错
org.json.JSONException: 字符 21 处的未终止数组 {jobs=[酒吧管理、贝克、酒吧服务、咖啡师、停车场服务、 厨师, 清洁服务, 烹饪和食物准备], lastUpdated=Tue 2016 年 6 月 28 日 10:22:03 GMT+05:30,类别=全职}
有时会出现这个错误
java.lang.ClassCastException: org.json.JSONObject 无法转换为 java.lang.String
【问题讨论】:
-
我假设您的 Json 在某些情况下已损坏,因此您会看到第一条错误消息。检查 Json 是否正确。
-
您的
data.add(Category);是什么意思?不应该是data.add(industry);吗? -
@Hao Qi 数据为List of Hashmap,类别为Hashmap
-
@Todor Kostov 如果它坏了,那么它也不能在棒棒糖上面工作,不是吗?
-
Json 是始终相同还是基于某些标准而有所不同?如果它不同,那么在某些情况下可能会被破坏。第一个错误非常清楚。