在Spring Boot 2.4(Jackson)中将字符串数据类型限制为仅请求正文的字符串类型 [英] Restrict string data type to only string types for request body in Spring boot 2.4 (Jackson)
问题描述
我已经按照以下步骤创建了请求POJO
I have created my request POJO as follows
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Notification {
@NotNull
private String clientId;
private String userId;
@NotNull
private String requestingService;
@NotNull
private String message;
@NotNull
private String messageType;
当我按以下方式发送请求正文时,它工作正常.
when I send request body as follow, it is working fine.
{
"clientId":"9563",
"userId":"5855541",
"requestingService":"cm-dm-service",
"message":"Document Created",
"messageType":"user-msg"
}
但是当我像下面这样发送时
But when I sent like below
{
"clientId":"9563",
"userId":true,
"requestingService":"cm-dm-service",
"message":"Document Created",
"messageType":"user-msg"
}
这是我的控制人
public ResponseEntity<Status> createNotification(@RequestBody @Valid Notification notification,
BindingResult bindingResult, HttpServletRequest request) throws AppException {
预期:抛出一些错误
实际:将 userId 的 true 值转换为杰克逊的字符串.
Actual: converting true value for userId to string by jackson.
请让我知道,有没有一种方法可以实现预期行为
please let me know is there a way to acheive the Expected behaviour
推荐答案
杰克逊NumberDeserializers.BooleanDeserializer
被编程为将布尔值转换为字符串.
The jackson NumberDeserializers.BooleanDeserializer
is programmed to convert boolean to String.
我们可以用我们的替代反序列化器,并阻止转换并抛出异常.
We can override the deserializer with ours and prevent the conversion and throw an exception instead.
我可以举一个例子,您尝试将其实施到您的问题陈述中.
I can give you an example, you try to implement it to your problem statement.
- 创建一个布尔反序列化类
public class MyDeser extends JsonDeserializer {
@Override
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonToken t = p.getCurrentToken();
if (t.isBoolean()) {
throw new Exception();
}
else if (t.isNumeric()) {
throw new Exception();
}
else if (t == JsonToken.VALUE_STRING) {
return p.getValueAsString();
}
return null;
}
}
- 现在将反序列化器注入到我们的应用程序中
@SpringBootApplication
@Configuration
public class Application {
@Bean
public SimpleModule injectDeser() {
return new SimpleModule().addDeserializer(String.class, new MyDeser());
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
这篇关于在Spring Boot 2.4(Jackson)中将字符串数据类型限制为仅请求正文的字符串类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!