Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonUnwrapped to deserialize GET request parameters

I have the following:

@RestController
public class MyController {

    @PostMapping
    MyDto test(@RequestBody MyDto myDto) {
        return myDto;
    }

    @GetMapping
    MyDto test2(MyDto myDto) {
        return myDto;
    }

    @Data
    static class MyDto {
        private String a;
        @JsonUnwrapped
        private MySecondDto secondDto;

        @Data
        static class MySecondDto {
            private String b;
        }
    }
}

However:

GET http://localhost:8080?a=a&b=b

returns

{
    "a": "a"
}

while

POST http://localhost:8080

{
    "a": "a",
    "b": "b"
}

returns

{
    "a": "a",
    "b": "b"
}

so it looks like @JsonUnwrapped and GET mapped Pojos don't work together as expexted. Any hint on how to use complex nested Pojos to accomodate GET request params ?

like image 717
Giuseppe Nespolino Avatar asked Feb 16 '26 08:02

Giuseppe Nespolino


2 Answers

I may be late, But spring uses jackson to deserialize the body, while it converts query parameters directly

You can, however, use resolvers or converters to redefine the way your parameters are converted

like image 196
Ugo Evola Avatar answered Feb 19 '26 00:02

Ugo Evola


You can use jackson deserializer and skip query parameters conversion in the following way:

  1. Use @RequestParam with Map<String, String>. Spring docs says: "If the method parameter is Map<String, String> or MultiValueMap<String, String> and a parameter name is not specified, then the map parameter is populated with all request parameter names and values." https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html
@GetMapping(value = BASE_URL)
public ResponseEntity<List<MyDto>> getDtos(@RequestParam Map<String, String> criteriaMap, Pageable pageable)
  1. Use ObjetMapper convertValue method to take adventage of Jackson library. You can use it inside getDtos body or write custom service for it.
ObjectMapper objectMapper = new ObjectMapper();
MyDto criteria = objectMapper.convertValue(criteriaMap, MyDto.class);

Then your @JsonUnwrapped annotation should work.

like image 39
Falcon Avatar answered Feb 19 '26 00:02

Falcon