我有以下结构
Public void Student(){
private string name;
private int age;
}
Public void Class(){
private string roomNo;
private Student student; //Student Object
}
Public void School(){
private string roomNo;
private String student; //String student
}
我正在尝试使用map struct映射这些
@Mapping(source = "java(student.toString())", target = "student")
School mapClassToSchool(@NonNull Class class);
我遇到以下错误
error: No property named "java(student.toString())" exists in source parameter(s). Did you mean "student"?
[javac] @Mapping(source = "java(student.toString())", target = "student")
[javac] ^
我尝试过此https://mapstruct.org/documentation/stable/reference/html/,但无法为我的用例提供简单的示例
我如何将student
映射为其string
表示形式
编辑:1
有可能做
@Mapping(expression = new GSON().toJson(clazz.getStudent()), target = "student")
School mapClassToSchool(@NonNull Class class);
答案 0 :(得分:2)
如果要使用表达式,则必须使用Mapping#expression
。无论您在表达式中定义什么,它都会在生成的代码中一对一设置。
例如
@Mapping(expression = "java(clazz.getStudent().toString())", target = "student")
School mapClassToSchool(@NonNull Class clazz);
另一种选择是也定义Student
和String
之间的映射方法,那么您将不需要为学生定义自定义@Mapping
。
例如
School mapClassToSchool(@NonNull Class clazz);
default String mapStudentToString(Student student) {
return student != null ? student.toString() : null;
}
请注意,class
是Java保留字。
School mapClassToSchool(@NonNull Class class)
:clazz
。