Modelmapper to convert from String to LocalDate

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

My DTO is having date field in String format. My entity is having date as LocalDate. Currently I am skipping it from map and then later manually explicitly setting it (String to Date and vis-versa).

is it possible to convert it automatically? I tried Converter inside spring bean but it gives me lot of compile errors (type Converter does not take parameters, does not override convert method - also lot of error for convert() as well).

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

I am not very familiar with modelmapper. Any help is greatly appreciated.

As suggested I tried with LocalDate for DTO but the problem is when I send this entity at front (REST call) I get following JSON.

"dateOfBirth": {    "year": 1972,    "month": "JANUARY",    "monthValue": 1,    "dayOfMonth": 4,    "dayOfWeek": "TUESDAY",    "era": "CE",    "dayOfYear": 4,    "leapYear": true,    "chronology": {       "id": "ISO",       "calendarType": "iso8601"    } } 

My front end developer need "YYYY-MM-DD".

回答1:

If you want to convert to LocalDate you need to create a Provider otherwise ModelMappercannot instantiate LocalDate because it hasn't a public default constructor.

Use this configuration and it will work:

 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); 

My tests has good output:

 String dateTest = "2000-09-27";  LocalDate dateConverted = modelmapper.map(dateTest, LocalDate.class);   System.out.println(dateConverted.toString()); //Output = 2000-09-27 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!