使用Jackson

时间:2017-07-01 15:40:26

标签: java json jackson dto

我有一个json:

{
"response": {
    "GeoObjectCollection": {
        "featureMember": [
            {
                "GeoObject": {
                    "description": "Country",
                    "name": "City",
                    "Point": {
                        "pos": "31.992615 45.057626"
                    }
                }
            },
            {
                "GeoObject": {
                    "description": "Country",
                    "name": "City",
                    "Point": {
                        "pos": "49.242414 49.895935"
                    }
                }
            }
        ]
    }
}

}

我创建了DTO:

GeographicCoordinateDto.java

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class GeographicCoordinateDto {
   @JsonProperty("description")
   private String location;
   @JsonProperty("name")
   private String cityName;
   @JsonProperty("Point")
   private GeographicCoordinatesDto geoCoordinates;
}

GeographicCoordinatesDto.java

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class GeographicCoordinatesDto {
   @JsonProperty("pos")
   private String geoCoordinates;
}

然后我得到JsonNode

List<JsonNode> responseArrayOfObjects = mapper.readValue(new URL(yandexGeoCoderRestUrl+address), ObjectNode.class).findValues("GeoObject");

我正在尝试转换为DTO

GeographicCoordinatesDto geo = mapper.convertValue(responseArrayOfObjects.get(0), GeographicCoordinatesDto.class);

但是,我是空对象:

GeographicCoordinatesDto(geoCoordinates=null)

可能出现什么问题?

更新

responseArrayOfObjects包含:

enter image description here

1 个答案:

答案 0 :(得分:2)

您正试图从pos对象获取GeographicCoordinatesDto,但它位于Point的{​​{1}}对象内。

您可以这样做:

GeographicCoordinatesDto

或为Point创建另一个类:

List<JsonNode> responseArrayOfObjects = mapper.readValue(new URL(yandexGeoCoderRestUrl+address), ObjectNode.class).findValues("Point");

并在@JsonIgnoreProperties(ignoreUnknown = true) class Point { @JsonProperty("pos") private String geoCoordinates; } 中使用它:

GeographicCoordinatesDto