【发布时间】:2017-09-13 18:29:26
【问题描述】:
假设我从我的后端获得了针对 Game 对象的以下 JSON 响应:
{
"id": 1,
"date_game": "2017-08-30",
"users": [
{
"id": 1,
"score": 50
},
{
"id": 2,
"score": 40
},
{
"id": 3,
"score": 18
},
{
"id": 4,
"score": 10
}
我想使用 Retrofit 反序列化这样的对象。为此,我有以下课程:
public class Game {
@SerializedName("id")
private int id;
@SerializedName("date_game")
private String date_game;
@SerializedName("users")
private List<PlayerInGame> liste_joueurs;
public class PlayerInGame {
@SerializedName("id")
private Player player;
@SerializedName("score")
private int score;
}
public class Player implements Serializable{
@SerializedName("id")
private long id;
@SerializedName("username")
private String username;
@SerializedName("email")
}
我的问题是我希望 users 标记中的 id 字段映射到 PlayerInGame.player.id 而不是 PlayerInGame.player,但我当前的代码无法按预期进行序列化。
编辑:我编写了一个自定义序列化程序来处理PlayerInGame 对象:
public class PlayerInGameDeserializer implements JsonDeserializer<PlayerInGame>{
@Override
public PlayerInGame deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Log.d("DEBUG", "IN DESERIALIZER");
JsonObject jsonObject = json.getAsJsonObject();
int id = jsonObject.get("id").getAsInt();
int score = jsonObject.get("score").getAsInt();
Player player = Player.PlayerBuilder().withId(id).build();
PlayerInGame pgame = new PlayerInGame(player, score);
Log.d("PlayerInGame ID", Long.toString(pgame.getPlayer().getId()));
Log.d("PlayerInGame SCORE", Integer.toString(pgame.getScore()));
return pgame;
}
}
【问题讨论】:
标签: java android json retrofit