簡體   English   中英

MapStruct:如何將屬性從“java.lang.Object”映射到“java.lang.String”

[英]MapStruct: How to map property from "java.lang.Object to "java.lang.String"

MapStrut 的新功能; 對象到字符串錯誤:

[錯誤] /util/LicenseMapper.java:[11,23] 無法將屬性“java.lang.Object license.customFields[].value”映射到“java.lang.String license.customFields[].value”。 考慮聲明/實現一個映射方法:“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 將一個字段的輸入作為對象,因為它可能是布爾值或字符串或任何內容,因此我已將其映射到對象中。 而在 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); 

你可以這樣做:

@Mapping(target = "yourTarget", source = "yourClass.custField.value")

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM