的Hashmap:
public HashMap<Perk, Boolean> perks;
public HashMap<Perk, Boolean> getPerks() {
return perks;
}
我如何保存(工作正常,我使用谷歌的GSON):
object.add("perks", builder.toJsonTree(player.perks));
保存预览:
"perks": {
"DAMAGE_AMPLIFIER": true
}
我如何尝试加载但不起作用,错误如下。
if (reader.has("perks")) {
jsonToMap(reader.get("perks").toString(), player);
}
jsonToMap方法:
public static void jsonToMap(String t, Player player) throws JSONException {
JSONObject jObject = new JSONObject(t);
Iterator<?> keys = jObject.keys();
while(keys.hasNext()) {
String key = keys.next().toString();
boolean value = jObject.getBoolean(key);
player.perks.put(Perk.valueOf(key), value);
}
}
错误:
java.lang.NullPointerException
at com.callisto.world.entity.impl.player.PlayerLoading.jsonToMap(PlayerLoading.java:730)
at com.callisto.world.entity.impl.player.PlayerLoading.getResult(PlayerLoading.java:684)
答案 0 :(得分:1)
如果我必须猜测perks
为空,那么当你执行put
时就会得到一个空指针。将其更改为:
public HashMap<Perk, Boolean> perks=new HashMap<>(); //We init the hashmap here so we can putt stuff after that
public HashMap<Perk, Boolean> getPerks() {
return perks;
}
您甚至可以将其更改为:
Map<Perk, Boolean> perks=new HashMap<>();
并使用界面而不是方法中的实现