用于动态响应行的Json反序列化器

时间:2015-09-09 13:22:20

标签: java json gson

使用GSON生成json响应的反序列化器是正确的方法吗?

{
     user: "me",
     red: {"some object"},
     green: {...}
     ...
     ....
     .....
  }

我想我需要一个像

这样的对象
class ColorResponse {
   String user;
   Map<String, Color> colorMap;
}

1 个答案:

答案 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;
        }
    }