2

So I am migrating all of my controllers to using a DTO object as previously they used the persistence objects.

I have chosen to make use of MapStruct for this.

My problem is I have seemingly lost the ability to apply @JsonView to this response, as now the response when applying the view is {} (empty).

My question is, should this be possible to combine MapStruct and Jackson serialisation or will I be required to create a DTO class for each of the views that I currently use?

My class structure is as follows:

@Entity
public class User {
    @JsonView(View.Summary.class)
    private Long id;
    @JsonView(View.Summary.class)
    private String name;
    // Etc
}

public class UserDto {
    @JsonView(View.Summary.class)
    private Long id;
    @JsonView(View.Summary.class)
    private String name;
    // Etc
}

@Mapper
public interface UserMapper {
    User toUser(UserDto userDto);
    UserDto toUserDto(User user);
}

public class UserController() {
    @JsonView(View.Summary.class)
    @RequestMapping(path = "/users", method = RequestMethod.GET, produces = "application/json")
    public Page<UserDto> userPage(@RequestParam MultiValueMap<String, String> filters, Pageable page) {
        return service.findAllUser(filters, page).map(mapper::toUserDto);
    }

    @JsonView(View.Summary.class)
    @RequestMapping(path = "/users/{id}", method = RequestMethod.GET, produces = "application/json")
    public UserDto singleUser(@PathVariable("id") Long id) {
        return mapper.toUserDto(service.findById(id));
    }
}
Mark Brown
  • 167
  • 2
  • 12
  • I couldn't reproduce the problem. Can you please post [MCVE](https://stackoverflow.com/help/mcve)? – Denis Zavedeev Dec 02 '18 at 17:33
  • 3
    Using MapStruct and `@JsonView` defeats the purpose of using MapStruct (in my opinion). Why not create an object per view? For example `UserSummaryDto` and map from your `User` into the `UserSummaryDto` this way you don't need to use `@JsonView` and JacksonWould deserialize everything properly. – Filip Dec 02 '18 at 17:40
  • Thanks for the suggest @Filip, that is the solution I went for in the end – Mark Brown Dec 04 '18 at 12:56

0 Answers0