Mapstruct - Mapping customModel to it's string representation

Viewed 197

I have following structures

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
}

I am trying to map these using map struct

@Mapping(source = "java(student.toString())", target = "student")
School mapClassToSchool(@NonNull Class class);

I am getting following error

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]                           ^

I tried to go through this https://mapstruct.org/documentation/stable/reference/html/ but cant simple example for my usecase

Ho do i map student to its string representation

Edit: 1

is it possible to do

@Mapping(expression = new GSON().toJson(clazz.getStudent()), target = "student")
School mapClassToSchool(@NonNull Class class);
1 Answers

If you want to use expressions then you have to use Mapping#expression. Whatever you define in the expression it will be set one to one in the generated code.

e.g.

@Mapping(expression = "java(clazz.getStudent().toString())", target = "student")
School mapClassToSchool(@NonNull Class clazz);

Another alternative is to also define a mapping method between Student and String, then you won't need to define a custom @Mapping for the student.

e.g

School mapClassToSchool(@NonNull Class clazz);

default String mapStudentToString(Student student) {
    return student != null ? student.toString() : null;
}

Just a note, class is a Java reserved word.

  • This doesn't compile: School mapClassToSchool(@NonNull Class class).
  • Use clazz instead: School mapClassToSchool(@NonNull Class clazz).
Related