Spring Rest中用Jackson优雅反序列化嵌套查询参数的方案
Can Jackson Deserialize These Nested Query Parameters to My Custom DTO?
Absolutely, Jackson can handle this scenario perfectly—you just need to use its annotation-based mapping to bridge the gap between your bracket-style query parameters and your desired DTO structure. Here's a step-by-step solution tailored to your use case:
1. Define Nested Helper DTO Classes
First, create classes that mirror the nested structure of your query parameters. This matches the datatable[pagination], datatable[sort], and related fields:
@Getter @Setter public class Pagination { private Integer page; private Integer pages; // Empty values will automatically deserialize to null private Integer perpage; } @Getter @Setter public class Sort { private String field; private String sort; } @Getter @Setter public class Pageable { private Pagination pagination; private Sort sort; private String query; }
2. Configure the Main DataDto Class
Use Jackson's @JsonProperty annotation to map the top-level datatable prefix to your pageable field, and map the snake_case w_id parameter to your camelCase wId field:
@Getter @Setter public class DataDto { // Maps all nested `datatable[...]` parameters to the Pageable object @JsonProperty("datatable") private Pageable pageable; // Maps the flat `w_id` parameter to the camelCase `wId` field @JsonProperty("w_id") private String wId; }
3. Key Notes for Smooth Deserialization
- Nested Parameter Handling: Jackson natively understands bracket-style parameters like
datatable[pagination][page]as nested object properties (equivalent todatatable.pagination.pagein dot notation). - Empty/Null Values: Empty query parameters (like
datatable[pagination][pages]=) will be deserialized tonullfor nullable fields (e.g.,Integer pages). - Duplicate Parameters: Your sample URL includes both prefixed (
datatable[pagination][page]) and unprefixed (pagination[page]) parameters. If you want to ignore the unprefixed ones, no extra work is needed—Jackson will only map fields specified by your annotations. If you need to support both, add@JsonAliasto relevant fields (e.g.,@JsonAlias({"pagination", "datatable[pagination]"})on thePageable.paginationfield). - Spring Integration: If using Spring Boot/MVC, accept the DTO with
@RequestBody(ensure the request usesapplication/x-www-form-urlencodedcontent type) or use@ModelAttribute—Spring leverages Jackson under the hood for parameter binding here.
Example Mapping Result
When you send your sample GET request, Jackson will correctly map:
datatable[pagination][page]=-2→dataDto.getPageable().getPagination().getPage() = -2datatable[sort][sort]=desc→dataDto.getPageable().getSort().getSort() = "desc"w_id=6453111→dataDto.getWId() = "6453111"
内容的提问来源于stack exchange,提问作者Denis Stephanov
相关产品推荐
相关产品推荐

