JSON 键只能是Strings。尝试以下使用自定义JsonSerializer 和JsonDeserializer 的解决方案。
自定义 JsonSerializer 将在序列化时将密钥(Player 对象)转换为 JSON String:
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class CustomMapSerializer implements JsonSerializer<Map<Player, Player>> {
@Override
public JsonElement serialize(Map<Player, Player> src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject json = new JsonObject();
Gson gson = new Gson();
for (Entry<Player, Player> entry : src.entrySet()) {
json.add(gson.toJson(entry.getKey()), gson.toJsonTree(entry.getValue()));
}
return json;
}
}
自定义 JsonDeserializer 以在反序列化期间将密钥 (JSON String) 转换回 Player 对象:
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
public class CustomMapDeserializer implements JsonDeserializer<Map<Player, Player>> {
@Override
public Map<Player, Player> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
Map<Player, Player> players = new HashMap<Player, Player>();
Gson gson = new Gson();
JsonObject object = json.getAsJsonObject();
for (Entry<String, JsonElement> entry : object.entrySet()) {
players.put(gson.fromJson(entry.getKey(), Player.class), gson.fromJson(entry.getValue(), Player.class));
}
return players;
}
}
serialization 和deserialization 参考以下示例:
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Solutiony {
public static void main(String[] args) {
Map<String, Integer> data = new HashMap<>();
data.put("value", 100);
Player p = new Player();
p.setFaction("0.9");
p.setPlayerName("x");
p.setTeamName("A");
p.setResources(data);
Player p2 = new Player();
p2.setFaction("1.0");
p2.setPlayerName("y");
p2.setTeamName("B");
p2.setResources(data);
Map<Player, Player> map = new HashMap<Player, Player>();
map.put(p, p2);
Gson gson = new GsonBuilder().registerTypeAdapter(map.getClass(), new CustomMapSerializer())
.registerTypeAdapter(map.getClass(), new CustomMapDeserializer())
.setPrettyPrinting().create();
//Serialization
String val = gson.toJson(map);
//De-serialization
Map<Player, Player> map2 = gson.fromJson(val, map.getClass());
}
}
序列化的JSON 看起来像:
{
"{\"playerName\":\"x\",\"faction\":\"0.9\",\"teamName\":\"A\",\"resources\":{\"value\":100}}": {
"playerName": "y",
"faction": "1.0",
"teamName": "B",
"resources": {
"value": 100
}
}
}