gpt4 book ai didi

java - FAIL_ON_UNKOWN_PROPERTIES 在 Jersey POST 上未按预期工作

转载 作者:行者123 更新时间:2023-11-30 07:24:23 25 4
gpt4 key购买 nike

使用this post作为引用,我整理了一个用于 POST 调用的基本 Jersey Controller 方法,如下所示:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response createVisit(Visit newVisit) {
LOGGER.info("Creating visit");

this.visits.add(newVisit);

return Response.ok(newVisit)
.build();
}

以下是我的 Visit 对象上的字段(省略了构造函数和 getter/setter,因为我认为它们与此处无关 - 如果它们有帮助,我可以添加它们):

public class Visit {
private VisitId id;
private AthleteId athleteId;
private CustomerId customerId;
private StoreId storeId;

private Instant createdUtc;
private Instant lastModifiedUtc;

}

当我在请求正文中以 JSON 格式传递有效的 Visit 对象字段时,我看到 Visit 对象已按预期成功填充在响应中。但是,如果我将不属于 Visit 对象一部分的字段添加到请求正文中,它们似乎会被忽略。

我看过很多帖子试图弄清楚如何禁用 FAIL_ON_UNKNOWN_PROPERTIES 属性,但我似乎遇到了相反的问题。我的理解是 FAIL_ON_UNKNOWN_PROPERTIES 默认为 true,但在这种情况下,当请求正文中的 JSON 对象与我的对象不匹配时,我希望收到错误响应代码(500?)我传递给我的 POST 方法。关于我在这里缺少什么有什么想法吗?

最佳答案

使用ContextResolver,如 the documentation 中所述。

@Provider
public class MyObjectMapperProvider implements ContextResolver<ObjectMapper> {

private final ObjectMapper mapper;

public MyObjectMapperProvider() {
mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}

@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}
}

然后您需要确保解析器已注册。如果您使用某种扫描机制来自动注册您的资源和提供程序,则应使用 @Provider 注释来选取此类

关于java - FAIL_ON_UNKOWN_PROPERTIES 在 Jersey POST 上未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37010301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com