JsonProperty for Java Records in Spring Boot controller

3.9k Views Asked by At

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();
    }
}
1

There are 1 best solutions below

0
On

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();
    }