使用GSON
生成json响应的反序列化器是正确的方法吗?
{
user: "me",
red: {"some object"},
green: {...}
...
....
.....
}
我想我需要一个像
这样的对象class ColorResponse {
String user;
Map<String, Color> colorMap;
}
答案 0 :(得分:0)
所以我的解决方案是自定义反序列化器
public class ColorDeserializer implements JsonDeserializer<ColorResponse> {
private List<String> colors;
public ColorDeserializer(List<String> colors) {
this.colors = colors;
}
@Override
public ColorResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject object = json.getAsJsonObject();
long timestamp = object.get("timestamp").getAsLong();
String username = object.get("user").getAsString();
ColorResponse colorResponse = new ColorResponse(timestamp, username);
for (String color: colors) {
JsonObject jsonObject = object.get(color).getAsJsonObject();
if (jsonObject != null) {
colorResponse.getColorMap().put(color, context.<Color>deserialize(jsonObject, Color.class));
}
}
return colorResponse;
}
}