-1

I can receive get request params to an object, but if there's a underscore_case param, how to convert to camelCase, for example:

@Slf4j
@RestController
@RequestMapping("/api/v1")
public class UserController {

    @GetMapping("/users")
    public String getUsers(
            UserQuery userQuery
    ) {
        log.info(userQuery.toString());
        return userQuery.toString();
    }
}
@Data
@NoArgsConstructor
public class UserQuery {

    @JsonProperty("user_name")
    private String userName;

    private Integer age;

}

when I send request:

GET /api/v1/users?user_name=zhangsan&age=20

then print UserQuery(userName=null, age=20)

how can I receive userName correctly?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
weiweiwei
  • 31
  • 5
  • 2
    The `@JsonProperty`-annotation seems wrong here; we do not receive a JSON, but query parameters. I am not sure, though, how to "rename" the parameter for deserialization. – Turing85 Aug 05 '23 at 16:38
  • @Turing85 yes, @JsonProperty("user_name") does't work here, I don't know how to make it work. – weiweiwei Aug 05 '23 at 16:44
  • 2
    Does it work if you replace `user_name` with `userName` in the URL? – Turing85 Aug 05 '23 at 16:59
  • @Turing85 If I replace user_name with userName, it work. But generally the param from front-end is UnderscoreCase. So I made this test and want to know the answer. – weiweiwei Aug 05 '23 at 17:03
  • 1
    i know. But I just wanted to ensure that the base functionality works. – Turing85 Aug 05 '23 at 17:03
  • 1
    Can you try to replace `@JsonProperty` with `@RequestParam`? – Turing85 Aug 05 '23 at 17:06
  • @Turing85 it does't work , it say "'@RequestParam' not applicable to field" – weiweiwei Aug 05 '23 at 17:07
  • 1
    `@RequestParam` would go in the `getUsers()`, not in the model - https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-methods/requestparam.html – OneCricketeer Aug 05 '23 at 17:09
  • 2
    Hm... I can't find a corresponding way to "rename" that field. One possible solution is of course to not receive an object, but an `int` and a `String` on the `@GET` method, which then must be annotated with `@RequestParam(...)`. – Turing85 Aug 05 '23 at 17:17
  • 1
    Related post - https://stackoverflow.com/questions/26612404/spring-map-get-request-parameters-to-pojo-automatically – OneCricketeer Aug 05 '23 at 17:18
  • @OneCricketeer I had read this, but there is a key point :the param is UnderscoreCase or camelCase. – weiweiwei Aug 05 '23 at 17:23
  • @Turing85 I know the way you just said, I just wondering: is there no way to resolve this problem? – weiweiwei Aug 05 '23 at 17:24
  • Java objects aren't required to be camelCase fields, underscore is acceptable, but a Map object would need to be used to accept both, and is shown in the Spring documentation – OneCricketeer Aug 06 '23 at 14:35

0 Answers0