gpt4 book ai didi

java - 如果在使用 jackson objectmapper 反序列化时字符串不是双引号,则抛出错误

转载 作者:行者123 更新时间:2023-12-03 11:18:17 24 4
gpt4 key购买 nike

我有一个 JSON:

{
"stringField" : 1234,
"booleanField": true,
"numberField": 1200.00
}
我使用对象映射器将 json 反序列化为:-
@Data
class SomeClass {
String stringField;
boolean booleanField;
float numberField;
}
我希望 objectMapper 抛出错误,因为根据 json 规范,字符串字段的值必须双引号。我怎样才能让 objectMapper 抛出错误?

最佳答案

您可以编写自定义字符串解串器。(我假设您使用的是 spring)

@Configuration
public class JacksonConfiguration {

@Bean
SimpleModule jacksonDeserializerConfiguration() {
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new StdDeserializer<String>(String.class) {
@Override
public String deserialize(JsonParser parser, DeserializationContext context)
throws IOException {
if (!parser.hasToken(JsonToken.VALUE_STRING)) {
//throw ex what do u want
throw new RuntimeException("String not include quote");
}
return StringDeserializer.instance.deserialize(parser, context);
}
});
return module;
}
}

关于java - 如果在使用 jackson objectmapper 反序列化时字符串不是双引号,则抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64101409/

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