简体   繁体   中英

Issue mapping Json with jackson

I'm having some issues mapping the next json in java:

{
  "aggregations": {
    "asMap": {
      "detail": {
        "name": "detail",
        "value": 35100
      },
      "listed": {
        "name": "listed",
        "value": 618
      }
    }
  },
  "docCount": 9,
  "key": "789028",
  "keyAsNumber": 789028,
  "keyAsText": {}
}

to the next java bean:

public class RankingValue  {
    private Integer adId;
    private Integer listed;
    private Integer detail;
    ...
    ...
}

is it posible to map using jackson? What i would like is to get value inside detail to detail on bean and value inside listed to listed on bean, and finally the key value to adId. is there other alternative to map this? Best way?

Thanks in advance.

I guess that you have to use a custom Deserializer. This seems to work:

public class RankingValueDeserializer extends JsonDeserializer<RankingValue> {

    @Override
    public RankingValue deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        Integer key = node.get("key").asInt();
        Integer detail = node.get("aggregations").get("asMap").get("detail").get("value").asInt();
        Integer listed = node.get("aggregations").get("asMap").get("listed").get("value").asInt();
        return new RankingValue(key, detail, listed);
    }
}

and your object will be something like

@JsonDeserialize(using = RankingValueDeserializer.class)
public class RankingValue  {

    private Integer adId;
    private Integer listed;
    private Integer detail;

    public RankingValue(Integer key, Integer listed, Integer detail) {
        this.adId = key;
        this.listed = listed;
        this.detail = detail;
    }

    @Override
    public String toString() {
        return "RankingValue [adId=" + adId + ", listed=" + listed
                + ", detail=" + detail + "]";
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM