我是新来的mapStruct,我不知道如何排除空字段。
这些类看起来像这样:
public class MyClass {
String reference;
Info info;
...
}
public class Info{
Long id;
List<String> parts = new ArrayList<>();
...
}
Run Code Online (Sandbox Code Playgroud)
这是映射器:
@Mapping(target = "info.id", source = "infoId")
public abstract MyClass toMyClass(RequestProto.line Line);
Run Code Online (Sandbox Code Playgroud)
因此,当它info.id为空时,我会使用带有空零件列表的参数MyClass进行实例化。info
MYCLASS(current)
{
reference: "aa",
info: {
parts: []
}
}
Run Code Online (Sandbox Code Playgroud)
我想要的是,当 为info.id空时info,参数为空。
MYCLASS(expected)
{
reference: "aa"
info: null
}
Run Code Online (Sandbox Code Playgroud)
我不知道如何实现这一目标。
我希望我解释了我自己。如果有人能给我带来一些启发,我将不胜感激
小智 2
您可以使用自己的逻辑:
@Mapping(target = "info", source = "Line", qualifiedByName = "info")
public abstract MyClass toMyClass(RequestProto.line Line);
@Named("info")
public Info mapInfo(RequestProto.line Line) {
if(infoId.isEmpty()) {
return null;
}
Info info = new Info();
info.setId(infoId);
return info;
}
Run Code Online (Sandbox Code Playgroud)
或者你可以为其创建新类:
@Mapper(uses = {InfoMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public MyClassMapper {
@Mapping(target = "info", source = "Line", qualifiedByName = "info")
public abstract MyClass toMyClass(RequestProto.line Line);
}
public class InfoMapper implements Function<Info, RequestProto.line> {
@Override
@Named("info")
public Info apply(RequestProto.line Line) {
//pseudo code, make it better based on your request object
if(infoId.isEmpty()) {
return null;
}
Info info = new Info();
info.setId(infoId);
return info;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3382 次 |
| 最近记录: |