【发布时间】:2019-11-28 05:01:26
【问题描述】:
Flight 对象具有如下属性:
@JsonProperty("OriginLocation")
private Location originLocation;
位置对象如下所示:
@JsonProperty("lat")
private double latitude;
@JsonProperty("lon")
private double longitude;
我正在映射到 FlightDto,其中的属性看起来像这样(注意:FlightDto 将 5 个左右的属性从 Flight 移动到 LocationDto ——这些都自动映射,除了纬度/经度):
private LocationDto origin;
LocationDto 如下所示:
private CoordinatesDto coordinates;
CoordinatesDto 如下所示:
private double latitude;
private double longitude;
所以...除了纬度/经度之外,所有属性都正确映射。映射应该是:
FlightDto.getOrigin().setCoordinates(new CoordinatesDto(Flight.getOriginLocation().getLatitude(),
Flight.getOriginLocation().getLongitude());
FlightDto.getOrigin() 中的其他字段以某种方式自动正确映射。
我试过了:
modelMapper.addMappings(new PropertyMap<Flight, FlightDto>() {
@Override
protected void configure() {
map().getOrigin().setCoordinates(new CoordinatesDto(source.getOriginLocation().getLatitude(),
source.getOriginLocation().getLongitude()));
// map().getDestination().setCoordinates(new CoordinatesDto(source.getDestinationLocation().getLatitude(),
// source.getDestinationLocation().getLongitude()));
}
});
但这实际上在启动时崩溃:
原因:java.lang.NullPointerException: null 在 org.xxx.yyy.flights.models.Location$ByteBuddy$NcO8GjcN.getLongitude(Unknown Source) ~[classes/:na] 在 org.xxx.yyy.config.ModelMapperConfig$2.configure(ModelMapperConfig.java:42) ~[classes/:na] 在 org.modelmapper.PropertyMap.configure(PropertyMap.java:389) ~[modelmapper-2.3.5.jar:na]
我不明白为什么 getLatitude() 有效,但 getLongitude() 不是为了一件事...但是可以说我注释掉了 getLongitude() 和硬编码 1... 看起来像二传手只在启动时调用一次,而不是为每条记录调用一次。
我还看到了一些使用 TypeMap 的示例,但我看不到如何从 1 个嵌套级别映射到 2 个嵌套级别,因为 LocationDto 已正确创建和填充,但 LocationDto.Coordinates 不是。
【问题讨论】:
标签: java spring modelmapper