public class Car {
private String make;
private int seatCount;
private CarType type;
//constructor, getters, setters etc.
}
CarDto.java
public class CarDto {
private String make;
private int seatCount;
private String type;
//constructor, getters, setters etc.
}
CarMapper.java
@Mapper
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
CarDto carToCarDto(Car car);
Car carDtoToCar(CarDto carDto);
}
用途:
public void shouldMapCarToDto() {
Car car = new Car( "Morris", 5, CarType.SEDAN );
// mapping Car to carDto
CarDto carDto = CarMapper.INSTANCE.carToCarDto(car);
}
3条答案
按热度按时间lvmkulzt1#
如果字段名匹配,或者定义了别名,则可以简单地序列化一个对象并反序列化到另一个对象;例如:
如果字段不是一对一对齐,则没有直接的方法
因此,您有一些其他选项
new Object2(object1)
或Object2.from(object1)
object2.setX(object1.getX()); // repeat for all fields
dw1jzc5e2#
ModelMapper,就像OneCricketeer说的,或者MapStruct可以完成将一个POJOMap到另一个POJO的工作。
bqf10yzr3#
您可以使用***MapStruct***,如下所示:
1.添加
MapStruct
依赖关系:示例-
Car.java
CarDto.java
CarMapper.java
用途:
更多详情-〉MapStruct