How convert string field to hashmap value with mapstruct java?

I want map accountNo to argument value with specific key(I mean key of hashmap), with mapstrcut. Any ideas?

Event is my target

    private Map<String, Object> argument;
    private LocalDateTime dateTime;

AccountRequest is my source

    private String accountNo;
    private LocalDateTime dateTime;

I have the mapper as below but I want the opposite one too.

    @Mapping(target = "accountNo", expression = "java(event.getArgument().get(key).toString())")
    AccountRequest eventToAccountRequest(Event event, String key);

    Event accountRequestToEvent(AccountRequest accountRequest); // this is my question

Answer

Currently there is no out-of-the-box support for mapping from a Bean into a Map. There is however an open feature request for this functionality.

This means that for your example you’ll need to do it in a custom mapping.

e.g.

    @Mapping(target = "argument", source = "accountNo", qualifiedByName = "accountNoToArgument")
    Event accountRequestToEvent(AccountRequest accountRequest);

    @Named("accountNoToArgument")
    default Map<String, Object> accountNotToArgument(String accountNo) {
        return accountNo == null ? null : Collections.singletonMap("accountNo", accountNo);
    }

This would make sure that the rest of the parameters are automatically mapped by MapStruct.


Side note about a better mapping for eventToAccountRequest. Instead of using an expression you can improve it with a custom mapping method and @Context. e.g.

    @Mapping(target = "accountNo", source = "argument", qualifiedByName = "argumentToAccountNo")
    AccountRequest eventToAccountRequest(Event event, @Context String key);

    @Named("argumentToAccountNo"
    default String argumentToAccountNo(Map<String, Object> argument, @Context key) {
        return argument == null : null : argument.get(key).toString();
    }

Using this you will avoid a potential NPE if event.getArgument() is null.