1

Controller

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<PaginatedResponse<User>> getAllUsers(
        @RequestParam(defaultValue = "") String q,
        @RequestParam(defaultValue = "") String[] fields,
        @RequestParam(defaultValue = "") String[] sort,
        @RequestParam(defaultValue = "50") Integer limit,
        @RequestParam(defaultValue = "0") Integer offset,

        @RequestParam(defaultValue = "") String userField1,
        @RequestParam(defaultValue = "") String userField2,
        @RequestParam(defaultValue = "") Boolean userField3,
        @RequestParam(defaultValue = "") ZonedDateTime userField4,
        @RequestParam(defaultValue = "")  String userRoleId5,
        @RequestParam(defaultValue = "")  Long userRoleId6,
        @RequestParam(defaultValue = "")  Long userRoleId7
) {
  //call to service
}

UserDTO

public class UserDTO {
    private String userField1;
    private String userField2;
    private boolean userField3;
    ZonedDateTime userField4;

    @JsonProperty("USERFIELD5")
    private String userField5;

    @JsonProperty("USERFIELD6")
    private Long userField6;

    @JsonProperty("USERFIELD7")
    private Long userField7;

    //getters and setters
}

user fields are used in GET /users parameter to filter the list of users in response. The current code works but I'm wondering if there is a better way to avoid this manual definition of the fields in the controller.

I considered using HahsMap to get all the request parameters but I opt out since I need to check if the passed parameter is valid.

letthefireflieslive
  • 11,493
  • 11
  • 37
  • 61
  • There is a way of matching request parameters to the DTO fields, but keep in mind that the name of request parameter must match with the field and there is no way to override the name as you suggested with the `@JsonProperty`. – Ihor M. Jun 06 '19 at 22:38

1 Answers1

-1

Use @ResponseBody like

@ResponseBody
@RequestMapping(value = "your mapping here", method = RequestMethod.GET)
public List<User> getUsers() {

}

and serialize your User entity attributes with Jackson or GSON w/e

With gson you can serialize your fields like

@SerializedName("user_id")
private Integer id;
Boldbayar
  • 862
  • 1
  • 9
  • 22