如果在使用杰克逊对象映射器反序列化时字符串未用双引号引起,则抛出错误

问题描述

我有一个JSON:

{
    "stringField" : 1234,"booleanField": true,"numberField": 1200.00
}

我使用对象映射器将json反序列化为:-

@Data
class SomeClass {
    String stringField;
    boolean booleanField;
    float numberField;
}

我希望objectMapper引发错误,因为String字段的值必须根据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;
    }
}
,

这应该可以解决您的问题。

class SomeClass {
    @JsonDeserialize(using=ForceStringDeserializer.class)
    public String stringField;
    public boolean booleanField;
    public float numberField;
}


class ForceStringDeserializer extends JsonDeserializer<String> {
    @Override
    public String deserialize(JsonParser jsonParser,DeserializationContext deserializationContext) throws IOException {
        if (jsonParser.getCurrentToken() != JsonToken.VALUE_STRING) {
            throw deserializationContext.wrongTokenException(jsonParser,JsonToken.VALUE_STRING,"Attempted to parse Integer to String but this is forbidden");
        }
        return jsonParser.getValueAsString();
    }
}
,

您只需要像这样设置杰克逊对象映射器

JsonFactory factory = new JsonFactory();
factory.disable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
ObjectMapper mapper = new ObjectMapper(factory)

这应该在序列化/反序列化期间引发错误

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...