【问题标题】:Not able to retrieve hashmap from sharedPreferences无法从 sharedPreferences 中检索 hashmap
【发布时间】: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 是始终相同还是基于某些标准而有所不同?如果它不同,那么在某些情况下可能会被破坏。第一个错误非常清楚。

标签: java android json hashmap


【解决方案1】:

尝试使用JSONObject object = new JSONObject(industry);

而不是JSONArray result = new JSONArray(data);

object.toString() 就像 {"Jobs":["Bar management","Baker","Bar service"],"lastUpdated":"Tue Jun 28 13:54:24 GMT+08:00 2016","CategoryName":"fulltime"}

result.toString() 就像[{"Jobs":["Bar management","Baker","Bar service"],"lastUpdated":"Tue Jun 28 13:54:24 GMT+08:00 2016","CategoryName":"fulltime"}]

我认为该对象是您真正想要的,并且在检索时也使用 JsonObject。

希望有帮助。

此外,您可以使用this 来验证您的结果。

【讨论】:

    【解决方案2】:

    问题是您存储的数组是 HashMaps 的 JSONArray。当您检索数组时,数组中的对象是字符串(代表 HashMap)。 JSONObject obj = new JSONObject((String) array.get(i)); 您正在尝试将其转换为 JSONObject。这就是问题所在。要么将每个字符串转换回 hashmap,要么可以使用 JSONObject 代替 HashMap 来存储数据

    public void storeInPrefs(){
        JSONArray data = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
    
            JSONObject industry = new JSONObject();
            ParseObject foundObject = list.get(i);
            try {
                industry.put("CategoryName", foundObject.get("category"));
                industry.put("lastUpdated", new Date());
                industry.put("Jobs", foundObject.getList("jobs"));
                data.put(industry);
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }
        SharedPreferences preferences = this.getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("Categories", data.toString());
        editor.commit();
    }
    

    并且要解析存储的数据并将其放入集合中,您可以这样做

    public void parseStoredData(){
        SharedPreferences pref = this.getPreferences(MODE_PRIVATE);
        String storedCollection = pref.getString("Categories", null);
        //Parse the string to populate your collection.
        ArrayList<HashMap<String, Object>> collection = new ArrayList<HashMap<String, Object>>();
        if (storedCollection != null) {
            try {
    
                JSONArray array = new JSONArray(storedCollection);
    
                for (int i = 0; i < array.length(); i++) {
                    try {
    
                        JSONObject object = array.getJSONObject(i);
                        HashMap<String,Object> item = new HashMap<String, Object>();
                        Iterator<String> it = object.keys();
    
                        while (it.hasNext()) {
                            String key = it.next();
                            item.put(key, object.get(key));
                        }
    
                        collection.add(item);
                    } catch (JSONException e) {
                            e.printStackTrace();
                    }
    
                }
    
            } catch (JSONException e) {
                Log.e("JSON", "while parsing", e);
            }
        }
    }
    

    在我看来,这对你来说很容易。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      • 1970-01-01
      相关资源
      最近更新 更多