Modelmapper将从String转换为LocalDate

use*_*612 5 spring modelmapper

我的DTO具有String格式的日期字段.我的实体的日期为LocalDate.目前我正在从地图中跳过它,然后手动显式设置它(String to Date,反之亦然).

可以自动转换吗?我在Spring bean中尝试了Converter但是它给了我很多编译错误(类型转换器不接受参数,不会覆盖转换方法 - 转换()也有很多错误).

@Bean
public ModelMapper studentModelMapper() {
....    
    Converter<String, LocalDate> toStringDate = new AbstractConverter<String, LocalDate>() {
        protected String convert(String source) {
            return source == null ? null : new LocalDate(source);
        }
    };
....
}
Run Code Online (Sandbox Code Playgroud)

我对modelmapper不太熟悉.任何帮助是极大的赞赏.

正如建议我尝试使用LocalDate for DTO,但问题是当我在前面发送此实体(REST调用)时,我得到了JSON.

"dateOfBirth": {
   "year": 1972,
   "month": "JANUARY",
   "monthValue": 1,
   "dayOfMonth": 4,
   "dayOfWeek": "TUESDAY",
   "era": "CE",
   "dayOfYear": 4,
   "leapYear": true,
   "chronology": {
      "id": "ISO",
      "calendarType": "iso8601"
   }
}
Run Code Online (Sandbox Code Playgroud)

我的前端开发人员需要"YYYY-MM-DD".

Pau*_*Pau 12

如果要转换为LocalDate需要创建一个Provider否则ModelMapper无法实例化,LocalDate因为它没有公共默认构造函数.

使用此配置,它将工作:

 ModelMapper modelmapper = new ModelMapper();

    Provider<LocalDate> localDateProvider = new AbstractProvider<LocalDate>() {
        @Override
        public LocalDate get() {
            return LocalDate.now();
        }
    };

    Converter<String, LocalDate> toStringDate = new AbstractConverter<String, LocalDate>() {
        @Override
        protected LocalDate convert(String source) {
            DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate = LocalDate.parse(source, format);
            return localDate;
        }
    };


    modelmapper.createTypeMap(String.class, LocalDate.class);
    modelmapper.addConverter(toStringDate);
    modelmapper.getTypeMap(String.class, LocalDate.class).setProvider(localDateProvider);
Run Code Online (Sandbox Code Playgroud)

测试输出:

 String dateTest = "2000-09-27";
 LocalDate dateConverted = modelmapper.map(dateTest, LocalDate.class);

 System.out.println(dateConverted.toString()); //Output = 2000-09-27
Run Code Online (Sandbox Code Playgroud)