Modelmapper to convert from String to LocalDate

后端 未结 3 746
终归单人心
终归单人心 2021-01-12 00:08

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 (Strin

3条回答
  •  失恋的感觉
    2021-01-12 00:28

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

    Use this configuration and it will work:

     ModelMapper modelmapper = new ModelMapper();
    
        Provider localDateProvider = new AbstractProvider() {
            @Override
            public LocalDate get() {
                return LocalDate.now();
            }
        };
    
        Converter toStringDate = new AbstractConverter() {
            @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);
    

    Test output:

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

提交回复
热议问题