JSON Deep Mapping

Is it possible to map a field that is deeper in json-response for a property in an object - in other words: convert json whose hierarchy to a flat object?

For example, I would like to annotate the user_id property of the Marker class 'links.user.id'. I've looked at GSON and Jackson but couldn't find a solution.

Json-Response for marker:

{
  "id": 791,
  "name": "Marker42",
  "links": {
    "user": {
      "href": "http://4242.com/users/970",
      "id": 970
  }
}

      

Data model:

public class Marker {
    @SerializedName("id")
    private int id;

    @SerializedName("name")
    private String name;

    @SerializedName("links.user.id")
    private int user_id;
}

      

+3


source to share


1 answer


It's not very good, but you can install your deserializer in GSON. I'm not that familiar with Jackson, but this tutorial shows a very similar method: http://www.baeldung.com/jackson-deserialization



public static class MarkerGSONDeserializer implements JsonDeserializer<Marker>{

    @Override
    public Marker deserialize(JsonElement data, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
        if(!data.isJsonObject()){
            return null;
        } else {
            JsonObject obj = data.getAsJsonObject();
            Marker res = new Marker();
            res.setId(obj.get("id").getAsInt());
            res.setName(obj.get("name").getAsString());
            res.setUserId(((obj.get("links").getAsJsonObject())).get("user").getAsJsonObject()).get("id").getAsInt();
            return res;
        }
    }

}

      

+1


source







All Articles