使用Jackson进行反序列化时,禁止将标量转换为字符串 [英] Disable conversion of scalars to strings when deserializing with Jackson

查看:118
本文介绍了使用Jackson进行反序列化时,禁止将标量转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想识别通过POST请求的请求正文发送的JSON中插入的不带引号(作为字符串)的数值:

I want to identify numerical values inserted without quotation marks (as strings) in JSON sent through the request body of a POST request:

例如,这将是错误的JSON格式,因为age字段不包含引号:

For example, this would be the wrong JSON format as the age field does not contain quotation marks:

{
  "Student":{
    "Name": "John",
    "Age":  12
  }
}

正确的JSON格式为:

The correct JSON format would be:

{
  "Student":{ 
    "Name": "John",
    "Age":  "12"
  }
}

在我的代码中,我已经将age字段的数据类型定义为String,因此"12"应该是正确的输入.但是,即使使用12,也不会引发任何错误消息.

In my code, I've defined the datatype of the age field as a String, hence "12" should be the correct input. However, no error message is thrown, even when 12 is used.

似乎Jackson会自动将数值转换为字符串.如何识别数值并返回消息?

It seems Jackson automatically converts the numerical values into strings. How can I identify numerical values and return a message?

这是我到目前为止尝试识别这些数值的方法:

This is what I tried so far to identify these numerical values:

public List<Student> getMultiple(StudentDTO Student) {
    if(Student.getAge().getClass()==String.class) {
        System.out.println("Age entered correctly as String");
    } else{
        System.out.println("Please insert age value inside inverted commas");
    }
}

但是,插入年龄时不带引号的情况下,这不会在控制台上打印"Please insert age value inside inverted commas".

However, this is not printing "Please insert age value inside inverted commas" to the console when the age is inserted without quotation marks.

推荐答案

如果您使用的是Spring Boot,默认情况下它将使用Jackson解析JSON.正如此问题中所述,Jackson中没有配置选项可以禁用此功能. .解决方案是注册一个自定义JsonDeserializer,一旦遇到JsonToken.VALUE_STRING

If you're using Spring boot, by default it uses Jackson to parse JSON. There's no configuration option within Jackson to disable this feature, as mentioned within this issue. The solution is to register a custom JsonDeserializer that throws an exception as soon as it encounters any other token than JsonToken.VALUE_STRING

public class StringOnlyDeserializer extends JsonDeserializer<String> {
    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        if (!JsonToken.VALUE_STRING.equals(jsonParser.getCurrentToken())) {
            throw deserializationContext.wrongTokenException(jsonParser, String.class, JsonToken.VALUE_STRING, "No type conversion is allowed, string expected");
        } else {
            return jsonParser.getValueAsString();
        }
    }
}

如果仅要将其应用于某些类或字段,则可以使用@JsonDeserialize批注进行批注.例如:

If you only want to apply this to certain classes or fields, you can annotate those with the @JsonDeserialize annotation. For example:

public class Student {
    private String name;
    @JsonDeserialize(using = StringOnlyDeserializer.class)
    private String age;

    // TODO: Getters + Setters
}

或者,您可以通过注册SimpleModule bean来注册自定义的Jackson模块,该bean使用StringOnlyDeserializer自动反序列化所有字符串.例如:

Alternatively, you can register a custom Jackson module by registering a SimpleModule bean that automatically deserializes all strings using the StringOnlyDeserializer. For example:

@Bean
public Module customModule() {
    SimpleModule customModule = new SimpleModule();
    customModule.addDeserializer(String.class, new StringOnlyDeserializer());
    return customModule;
}

这类似于欧根(Eugen)的建议.

如果现在运行您的应用程序,并且您经过了无效的期限,例如1212.3[12],它将抛出异常,并显示以下消息:

If you run your application now, and you pass an invalid age, such as 12, 12.3 or [12]it will throw an exception with a message like:

JSON parse error: Unexpected token (VALUE_NUMBER_FLOAT), expected VALUE_STRING: Not allowed to parse numbers to string; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (VALUE_NUMBER_FLOAT), expected VALUE_STRING: Not allowed to parse numbers to string\n at [Source: (PushbackInputStream); line: 3, column: 9] (through reference chain: com.example.xyz.Student[\"age\"])

这篇关于使用Jackson进行反序列化时,禁止将标量转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆