【发布时间】:2016-04-25 19:25:25
【问题描述】:
我正在尝试将 HashMap 保存到 SharedPreferences 中,但在加载地图时出现此错误:
java.lang.ClassCastException: org.json.JSONArray 无法转换为 java.util.List
我修改了我在网上找到的代码,但我不明白为什么会出现这个错误。
代码如下:
public static Map<String, List<Integer>> loadMap() {
Map<String,List<Integer>> outputMap = new HashMap<>();
SharedPreferences pSharedPref = MainActivity.getContextofApplication().getSharedPreferences(NETWORK_PREF, Activity.MODE_PRIVATE);
try{
if (pSharedPref != null){
String jsonString = pSharedPref.getString(RSSI_MAP, (new JSONObject()).toString());
JSONObject jsonObject = new JSONObject(jsonString);
Iterator<String> keysItr = jsonObject.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
List<Integer> value = (List<Integer>) jsonObject.get(key);
outputMap.put(key, value);
}
}
}catch(Exception e){
e.printStackTrace();
}
return outputMap;
}
public void saveRSSI() {
SharedPreferences pref = MainActivity.getContextofApplication().getSharedPreferences(NETWORK_PREF,Activity.MODE_PRIVATE);
JSONObject jsonObject = new JSONObject(this.RSSImap);
String jsonString = jsonObject.toString();
SharedPreferences.Editor editor = pref.edit();
editor.putString(RSSI_MAP, jsonString);
editor.commit();
}
【问题讨论】:
标签: java android json dictionary sharedpreferences