zaf187
zaf187

Reputation: 533

Using Java Jackson how to map a json that contains a list of maps to java pojo

I have been struggling with this issue for a couple days now.

Let's say my json response is:

{
"ignoreMe": -1,
"ignoreMeToo": "Not interested in this",
"valuableInfo": [{
        "Info1": {
            "key1": 0.0537,
            "key2": 0.0759
        }
    }, {
        "Info2": {
            "key2": 0.0444,
            "key4": 0.2345
        }
    }
]}

From this response i want to be able to map to my custom pojo object, which should look like this;

@JsonIgnoreProperties(ignoreUnknown = true)
public class ResponseDTO{
   private List<Map<String, Double>> valuableInfo;

    public ResponseDTO(List<Map<String, Double>> valuableInfo) {
        this.valuableInfo = valuableInfo;
    }

    public List<Map<String, Double>> getvaluableInfo() {
        return valuableInfo;
    }

    public void setvaluableInfo(List<Map<String, Double>> valuableInfo) {
        this.valuableInfo = valuableInfo;
    }
}

How do i setup my mapper to perform this conversion using just;

mapper.readValue(jsonResponse, ResponseDTO.class)

Upvotes: 2

Views: 2596

Answers (2)

Golam Mazid Sajib
Golam Mazid Sajib

Reputation: 9457

Observe carefully your json. Here valuableInfo contains List of objects. And every object contains Map< String,Object >. Then you class need to be like:

@JsonIgnoreProperties(ignoreUnknown = true)
public class ResponseDTO{
private List<Map<String, Map<String, Double>>> valueableInfo;

@JsonCreator
public ResponseDTO(@JsonProperty("valuableInfo") List<Map<String, Map<String, Double>>> valuableInfo){
    this.valueableInfo = valuableInfo;
}

public List<Map<String, Map<String, Double>>> getValueableInfo() {
    return valueableInfo;
}

public void setValueableInfo(List<Map<String, Map<String, Double>>> valueableInfo) {
    this.valueableInfo = valueableInfo;
}
}

Upvotes: 0

Lino
Lino

Reputation: 19910

I guess your error is, that Jackson can't find a suitable no-arg constructor for ResponseDTO (because there is none). To overcome this you can work with the @JsonCreator and @JsonProperty annotations. See the changed constructor:

@JsonCreator
public ResponseDTO(@JsonProperty("valuableInfo") List<Map<String, Double>> valuableInfo){
    this.valuableInfo = valuableInfo;
}

The rest of the code can stay the same.

This just tells jackson that it should inject the property with name "valuableInfo" into that constructor.

Upvotes: 5

Related Questions