NullPointerException when trying to define a custom PropertyMap

后端 未结 3 808
灰色年华
灰色年华 2020-12-21 02:01

I\'m using ModelMapper the following way :

I have a few converter classes that are Spring components and they register custom ModelMapper mappings

@C         


        
3条回答
  •  情深已故
    2020-12-21 02:52

    I think this is ultimately due to the fact that ModelMapper can not instantiate TimeZone objects (nor LocalDateTime etc.) at the time of configuring the mapper.

    Actually you don't have to configure anything.

    ModelMapper mapper = new ModelMapper();
    
    Foo foo = new Foo();
    foo.setTimeZone(TimeZone.getDefault());
    
    FooModel model = mapper.map(foo, FooModel.class);
    System.out.println(model.getTimeZoneId()); // "Europe/Berlin" here
    

    This works for me. ModelMapper found out that you want to map the TimeZone's property ID to FooModel's property timeZoneId.

    Nevertheless, just in case you want to do that manually: Following the docs quickly, I found the concept of converters. Using a Converter which converts TimeZone to String you can do this:

    ModelMapper mapper = new ModelMapper();
    TypeMap typeMap = mapper.createTypeMap(Foo.class, FooModel.class);
    Converter tzConverter = ctx -> ctx.getSource().getID() + "!!!";
    typeMap.addMappings(map -> {
        map.using(tzConverter).map(Foo::getTimeZone, FooModel::setTimeZoneId);
    });
    
    Foo foo = new Foo();
    foo.setTimeZone(TimeZone.getDefault());
    
    FooModel model = mapper.map(foo, FooModel.class);
    System.out.println(model.getTimeZoneId()); // "Europe/Berlin!!!" here
    

提交回复
热议问题