java - MapStruct:如何从 "java.lang.Object to "java.lang.String 映射属性”

标签 java gson dto mapstruct mapper

MapStrut 新手;对象到字符串错误:

[ERROR] /util/LicenseMapper.java:[11,23] Can't map property "java.lang.Object license.customFields[].value" to "java.lang.String license.customFields[].value". Consider to declare/implement a mapping method: "java.lang.String map(java.lang.Object value)".

代码:

@Mapper
public interface LicenseMapper {
    List<License> jsonToDao(List<com.integrator.vo.license.License> source);
}

vo.license 包含具有属性为的 CustomFields 列表

@SerializedName("Value")
@Expose
private Object value;

Json 将一个字段作为对象输入,因为它可能是 boolean 值、字符串或任何其他内容,因此我已将其映射到对象中。而在 dao 层中,String 中有相同的字段。 (在自定义映射器中,我只是 String.valueof 但不确定如何使用 Mapstrut 来实现它)

谁能告诉我 LicenseMapper 中需要进行哪些设置才能将对象转换为字符串?

许可证结构 - 来源和目的地:

.
.
private String notes;
private Boolean isIncomplete;
private List<CustomField> customFields = null;
private List<Allocation> allocations = null;

源中的自定义字段结构(删除了 gson 注释):

.
.
private String name;
private Object dataType;
private Object value;
<小时/>

目标中的自定义字段结构

private String name;
private String datatype;
private String value;

最佳答案

您可以尝试将注解@Mapping与表达式一起使用

@Mapping(expression = "java( String.valueOf(source.getValue()) )", target = "value")
List<License> jsonToDao(List<com.integrator.vo.license.License> source);

更新

@Mapper
public interface LicenseMapper {
LicenseMapper MAPPING = Mappers.getMapper(LicenseMapper.class);

List<License> entityListToDaoList(List<com.integrator.vo.license.License> source);

License entityToDao(com.integrator.vo.license.License source);

List<CustomField> customFieldListToCustomFieldList(List<*your custom field path*CustomField> source);

@Mapping(expression = "java( String.valueOf(source.getValue()) )", target = "value")
CustomField customFieldToCustomField(*your custom field path*CustomField source);
}

在你的代码中

import static ***.LicenseMapper.MAPPING;

***
List<License> myList = MAPPING.jsonToDao(mySource); 

关于java - MapStruct:如何从 "java.lang.Object to "java.lang.String 映射属性”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59539506/

相关文章:

java - 使用 Google GSON 的 Lotus Domino Java 安全问题

java - Gson json解析不起作用

java - 我正在按反向或自然顺序对 java 中的日期列表进行排序,但它是按年份分组的

javascript - 在集成 React native 和 android 应用程序时更改 MainActivity 条目

java - Google JSON,反序列化类并正确设置类字段值

java - 使用 MapStruct 将抽象类映射到 DTO

java - 初始化 DTO 中的字段

java - 我应该在哪里存储微服务的外部客户端 DTO?

java - 将 BlackBerry 应用程序与 Flurry 集成

java - 如何更改此方法以返回字符串列表而不是字符串?