【发布时间】:2015-03-16 20:02:34
【问题描述】:
不知何故,我无法从使用 Gson 制作的 HashMap 中检索 Double。
Map<Integer, Double> ratingMap = (Map<Integer, Double>) new GsonBuilder()
.create().fromJson(json, Map.class);
Integer ifilmId = filmId;
Double rating = ratingMap.get(ifilmId);
在这段代码中,我验证了 ratingMap 包含 {2=5.0},但是当我执行 ratingMap.get(ifilmId)(我验证 ifilmId 实际上是 2)时,变量 rating 为空。我在这里错过了什么吗?
我通过以下方式创建 HashMap:
if (json.equals("")) {
// noting ever saved
ratingMap = new HashMap<Integer, Integer>();
ratingMap.put(filmId, rating);
} else {
ratingMap = (Map<Integer, Integer>) new GsonBuilder().create()
.fromJson(json, Map.class);
ratingMap.put(Integer.valueOf(filmId), rating);
}
我让 Gson 将 Integer 格式化为 Double,这似乎可以正常工作,但我无法检索它。
总代码,包括保存到 Android 的 SharedPreferences
public void saveRating(int rating, int filmId) {
SharedPreferences sharedPref = context.getSharedPreferences(
LOCAL_MEM_KEY, 0);
String json = sharedPref.getString(LOCAL_MAP_RATING_KEY, "");
Map<Integer, Integer> ratingMap;
if (json.equals("")) {
// noting ever saved
ratingMap = new HashMap<Integer, Integer>();
ratingMap.put(filmId, rating);
} else {
ratingMap = (Map<Integer, Integer>) new GsonBuilder().create()
.fromJson(json, Map.class);
ratingMap.put(Integer.valueOf(filmId), rating);
}
json = new GsonBuilder().create().toJson(ratingMap, Map.class);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(LOCAL_MAP_RATING_KEY, json);
editor.commit();
}
/*
* returns null if no rating found
*/
public Map<Integer, Integer> getRatingFor(int filmId) {
SharedPreferences sharedPref = context.getSharedPreferences(
LOCAL_MEM_KEY, 0);
String json = sharedPref.getString(LOCAL_MAP_RATING_KEY, "");
if (json.equals("")) {
return null;
}
Map<Integer, Integer> ratingMap = (Map<Integer, Integer>) new GsonBuilder()
.create().fromJson(json, Map.class);
Log.d("map", ratingMap.toString());
Integer ifilmId = filmId;
Integer rating = ratingMap.get(ifilmId);
if(rating == null) { //because of this we have to prevent a 0 rating
return null;
} else {
Map<Integer, Integer> returnMap = new HashMap<Integer, Integer>();
returnMap.put(filmId, rating.intValue());
return returnMap;
}
}
【问题讨论】:
-
尝试执行
map.put(2, 4.0),然后打印map。看看你得到了什么。 -
您创建了一个
Map<Integer, Integer>并尝试获取一个Map<Integer, Double>? -
@AlexisC。是的。 Gson 确实正确格式化了它。当我将检索到的 Map 更改为“Map
”时,问题仍然存在。 -
你说
Log.d("map", ratingMap.toString());打印{2=5.0}并且ifilmId是2,你得到null? -
你能尝试发布一个小程序来演示这个问题吗?我认为它与
SharedPreferences无关,因此您尝试保存的带有 JSON 的简单 Java 程序就可以了。