如何使用ModelMapper转换不同的对象类型(不是等于类)
我想在项目中使用ModelMapper。我知道如何在基本级别上使用ModelMapper。
有我的实体课程:
public class User {
private String userId;
private String name;
private AccountType accountType;
}
public class AccountType {
private int id;
private String name;
}
还有我的响应类:
public class UserModel {
private String userId;
private String name;
private boolean accountType;
}
,我想要什么?
response: {
"userId": "12345",
"name": "Gokhan",
"accountType": false
}
我想将此响应转换为以下:
User: {
"userId": "12345",
"name": "Gokhan",
"AccountType " : {
"id" : "2"
"name" : "",
}
}
我的意思是,
if(response.accountType)
user.getAccountTpe.setId(1);
else user.getAccountTpe.setId(2);
注:我以JSON格式写了“用户”到底。但是我需要在Java中。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要自定义转换器:
从上下文中获取源对象,如果初始化(有时不是),获取目标对象。您可以使用MM的其他一些实例来避免使用手动匹配名称的设置字段(例如
userId
)。然后,您需要在MM实例 -
mapper.addconverter(new UserConverter());
上注册转换器。主要测试内容:
我建议在模型映射器上阅读一些其他资源 - 喜欢指南 ,此所以问题。
You need custom converter:
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:
I would sugges to read some additional resources on model mapper - like this guide, and this SO question.