0

I want to use modelmapper on my project. I know how can I use modelmapper on basic level.

There is my Entity classes:

public class User {
    private String userId;
    private String name;
    private AccountType accountType;
}

public class AccountType {
    private int id;
    private String name;
}

And there is my response class:

public class UserModel {
    private String userId;
    private String name;
    private boolean accountType;
}

So what I want?

response: {
    "userId": "12345",
    "name": "Gokhan",
    "accountType": false
}

I want to convert this response to following:

User: {
    "userId": "12345",
    "name": "Gokhan",
    "AccountType " : {
        "id" : "2"
        "name" : "",
    }
}

I mean,

if(response.accountType) 
    user.getAccountTpe.setId(1);
 else user.getAccountTpe.setId(2);

NOTE: I wrote "User" in JSON format in the end. But I need it in JAVA.

Gokhan
  • 41
  • 4

1 Answers1

0

You need custom converter:

public class UserConverter implements Converter<UserModel, User> {

    @Override
    public User convert(MappingContext<UserModel, User> context) {
        UserModel source = context.getSource();
        User destination = context.getDestination() == null ? new User() : context.getDestination();
        destination.setUserId(source.getUserId());
        destination.setName(source.getName());
        int accountTypeId = source.isAccountType() ? 1 : 2;
        AccountType accountType = new AccountType();
        accountType.setId(accountTypeId);
        accountType.setName("");
        destination.setAccountType(accountType);
        return destination;
    }
}

Get source object from context, get destination object, if initialized(sometimes it's not). You could use some other instance of mm to avoid setting fields with matching names manually(like userId, for example).

Then you need to register converter with your mm instance - mapper.addConverter(new UserConverter());.

Main to test stuff:

public class ConfMain {

    public static void main(String[] args) {
        ModelMapper mapper = new ModelMapper();
        //register your custom converter
        mapper.addConverter(new UserConverter());
        //test data
        UserModel model = new UserModel();
        model.setUserId("12345");
        model.setName("Gokhan");
        model.setAccountType(true);

        User user = mapper.map(model, User.class);
        System.out.println("user id - " + user.getUserId());
        System.out.println("user name - " + user.getName());
        System.out.println("account id - " + user.getAccountType().getId());
    }
}

I would sugges to read some additional resources on model mapper - like this guide, and this SO question.

Chaosfire
  • 4,818
  • 4
  • 8
  • 23