1

I try to use Java records in Spring Boot controller with @JsonProperty annotation but Jackson does not bind values to record fields.

Example:

public record SimpleQuery(
       @JsonProperty("simple_text") String text
) {}

@RestController
public class SimpleController {
    @GetMapping
    public String get(SimpleQuery query) {
        return query.text();
    }
}

I would like to call /?simple_text=test, but it only gets /?text=test. Please, help me to resolve this problem on Spring Boot 2.6.6 (Java 17).

Additional:

UPD: It works great with @PostRequest+@RequestBody:

@RestController
public class SimpleController {
    @PostMapping
    public String get(@RequestBody SimpleQuery query) {
        return query.text();
    }
}
dimon4ezzz
  • 11
  • 2
  • 3
  • Does this answer your question? [(Spring MVC / Jackson) Mapping query parameters to @ModelAttribute: LOWERCASE\_WITH\_UNDERSCORE to SNAKE\_CASE fails](https://stackoverflow.com/questions/43503977/spring-mvc-jackson-mapping-query-parameters-to-modelattribute-lowercase-wi) – Matthias Apr 06 '22 at 16:05
  • @Matthias do you suggest me add `mapper.convertValue(query)`? it doesn't work with empty params – dimon4ezzz Apr 07 '22 at 07:44
  • I'd like to get simple code without additional calls – dimon4ezzz Apr 08 '22 at 04:12

1 Answers1

0

This should work even when url has no request parameters (SpringBoot 2.6.6, Java 17):

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static record SimpleQuery(@JsonProperty("simple_text") String text) {}

    @GetMapping
    public String get(@RequestParam Map<String, String> map) {
        SimpleQuery query = new ObjectMapper().convertValue(map, SimpleQuery.class);
        return query.text();
    }
Delta George
  • 2,560
  • 2
  • 17
  • 11