【问题标题】:Convert ObjectNode to Java Object using Jackson使用 Jackson 将 ObjectNode 转换为 Java 对象
【发布时间】:2017-07-01 15:40:25
【问题描述】:

我有一个 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 包含:

【问题讨论】:

  • 我会检查列表中的所有JsonNodes。读取 JSON 时可能出错了?

标签: java json jackson dto


【解决方案1】:

您正试图从GeographicCoordinatesDto 对象中获取pos,但它位于GeographicCoordinatesDtoPoint 对象内。

您可以这样做:

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

或为 Point 创建另一个类:

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

并在GeographicCoordinatesDto中使用它:

@JsonIgnoreProperties(ignoreUnknown = true)
class GeographicCoordinatesDto {
   @JsonProperty("Point")
   private Point point;
}

【讨论】:

  • 我犯了一个错误。取而代之的是GeographicCoordinateDto.class,我写的是GeographicCoordinatesDto.class
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-25
  • 1970-01-01
  • 1970-01-01
  • 2018-07-19
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
相关资源
最近更新 更多