Reputation: 533
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
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
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