在表示查询参数作为对象的情况下,杰克逊注释被忽略

发布于 2025-01-09 22:25:56 字数 1201 浏览 0 评论 0原文

因此有一个简单的 GET 端点能够接受一些 url-params。为了以更优雅的方式与它们一起工作,正在使用 POJO。此外,所有 POJO 字段都使用 swagger 注释进行注释。

@GetMapping
public Object getSomething(@Valid QueryParams queryParams,
                           HttpServletRequest request) {
   // do smth with queryParams
   return something
}

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ApiModel(value = "QueryParams", description = "some description")
public class QueryParams {
    //some other fields

    @ApiModelProperty(value = "Some description", example = "false")
    @JsonDeserialize(using = StrictBooleanDeserializer.class)
    @JsonProperty("is_archived")
    private Boolean isArchived;
    
    //some other fields
}

问题在于,没有 Jackson 注释实际应用于带注释的字段。不会调用 StrictBooleanDeserializer 内部的代码。

我知道有以下解决方法

@Autowired
private ObjectMapper objectMapper;

@GetMapping
public Object getSomething(Map<String, String> params,
                           HttpServletRequest request) {
   QueryParams queryParams = objectMapper.convertValue(params, QueryParams.class)
   // do smth with queryParams
   return something
}

但是这样我们就失去了声明性验证和所有的招摇描述。 我认为必须有一种方法可以同时使用所有提到的功能,而无需太多开销。

So there is a simple GET endpoint which is able to accept some url-params. In order to work with them in more elegant way the POJO is being used. Also, all the POJO fields are annotated with swagger annotations

@GetMapping
public Object getSomething(@Valid QueryParams queryParams,
                           HttpServletRequest request) {
   // do smth with queryParams
   return something
}

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ApiModel(value = "QueryParams", description = "some description")
public class QueryParams {
    //some other fields

    @ApiModelProperty(value = "Some description", example = "false")
    @JsonDeserialize(using = StrictBooleanDeserializer.class)
    @JsonProperty("is_archived")
    private Boolean isArchived;
    
    //some other fields
}

The problem is that no Jackson annotation is actually applied to annotated fields. The code inside StrictBooleanDeserializer is not invoked.

I know there is the following workaround

@Autowired
private ObjectMapper objectMapper;

@GetMapping
public Object getSomething(Map<String, String> params,
                           HttpServletRequest request) {
   QueryParams queryParams = objectMapper.convertValue(params, QueryParams.class)
   // do smth with queryParams
   return something
}

But in this way we lose the declarative validation and all the swagger descriptions.
I think there has to be a way to use all the mentioned features together without much of overhead.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文