I want to set some objects as key of hashmap.And i need to save this hashmap to shared preferences. Given below is my code.
public void saveDetailsMap(MyModel model, int type) {
HashMap<NVRModel, Integer> ipMap = getAddressMap();
ipMap.put(nvrModel, type);
JSONObject jsonObject = new JSONObject(ipMap);
String jsonString = jsonObject.toString();
settings.edit().putString(MAP, jsonString).commit();
}
public HashMap<MyModel, Integer> getAddressMap() {
HashMap<MyModel, Integer> ipMap = new HashMap<MyModel, Integer>();
try {
String jsonString = settings.getString(MAP,
(new JSONObject()).toString());
JSONObject jsonObject = new JSONObject(jsonString);
Iterator keysItr = jsonObject.keys();
while (keysItr.hasNext()) {
MyModel key = (MyModel)keysItr.next();
Integer value = (Integer) jsonObject.get(key.toString());
ipMap.put(key, value);
}
} catch (Exception e) {
e.printStackTrace();
}
return ipMap;
}
But i am getting this exception
java.lang.ClassCastException: com.model.MyModel cannot be cast to java.lang.String
in below line.
JSONObject jsonObject = new JSONObject(ipMap);
How can i resolve this?
The key of a javascript object has to be of type String. Therefore you can not use
HashMap<NVRModel, Integer> ipMap
as the constructor argument of a JSONObject.