0

Is the a right way to make a deserializer for json response which looks like below to pojo using GSON?

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

I think I need a object somethink like

class ColorResponse {
   String user;
   Map<String, Color> colorMap;
}
Gorets
  • 2,434
  • 5
  • 27
  • 45

2 Answers2

0

I'm afraid that the solution that you are trying to achieve is not possible because colorMap is not a property of the JSON, the JSON should be like

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

Then what you need right now is a custom deserializer which iterates over JSONObjects of the response. Custom JSON deserializer using Gson this is a good example of how to deserialize with custom code and GSON.

Basically you have to register a custom deserializer for the class ColorResponse which you do something like:

deserialize() {
    ColorResponse response = new ColorResponse();
    List<Color> colors = new ArrayList<>();
    response.setName(json.getAsJsonObject().get("name").asString());
    for (Entry<String, JsonElement> entry : json.entrySet()) {
        if (!entry.getKey().equals("name")) {
           colors.add(new Color(entry.getKey(), entry.getValue()));
        }
    }
}

This code is just to show how can that be done, I have written it in the fly and I am not sure if it will compile but the key is that if you will only have that name will be constant, so the rest are colors, then just add all the colors to a List, Map, or whatever you want.

Community
  • 1
  • 1
Javier Diaz
  • 1,791
  • 1
  • 17
  • 25
0

So my solution is custom deserializer

  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;
        }
    }
Gorets
  • 2,434
  • 5
  • 27
  • 45