我想识别通过POST请求的请求正文发送的JSON中插入的不带引号(作为字符串)的数值:
例如,这将是错误的JSON格式,因为age字段不包含引号:
{
"Student":{
"Name": "John",
"Age": 12
}
}
正确的JSON格式为:
{
"Student":{
"Name": "John",
"Age": "12"
}
}
在我的代码中,我已将age字段的数据类型定义为String,因此“ 12”应该是正确的输入.但是,即使使用12,也不会引发任何错误消息.
杰克逊似乎自动将数值转换为字符串.如何识别数值并返回消息?
到目前为止,我一直在尝试识别这些数值:
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");
}
}
但是,如果插入不带引号的年龄,则不会在控制台上打印“请在反逗号内插入年龄值”.
解决方法:
默认情况下,当目标字段为String类型时,Jackson将标量值转换为String.这个想法是为String类型创建一个自定义反序列化器,并注释掉转换部分:
package jackson.deserializer;
import java.io.IOException;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
public class CustomStringDeserializer extends StringDeserializer
{
public final static CustomStringDeserializer instance = new CustomStringDeserializer();
@Override
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
if (p.hasToken(JsonToken.VALUE_STRING)) {
return p.getText();
}
JsonToken t = p.getCurrentToken();
// [databind#381]
if (t == JsonToken.START_ARRAY) {
return _deserializeFromArray(p, ctxt);
}
// need to gracefully handle byte[] data, as base64
if (t == JsonToken.VALUE_EMBEDDED_OBJECT) {
Object ob = p.getEmbeddedObject();
if (ob == null) {
return null;
}
if (ob instanceof byte[]) {
return ctxt.getBase64Variant().encode((byte[]) ob, false);
}
// otherwise, try conversion using toString()...
return ob.toString();
}
// allow coercions for other scalar types
// 17-Jan-2018, tatu: Related to [databind#1853] avoid FIELD_NAME by ensuring it's
// "real" scalar
/*if (t.isScalarValue()) {
String text = p.getValueAsString();
if (text != null) {
return text;
}
}*/
return (String) ctxt.handleUnexpectedToken(_valueClass, p);
}
}
现在注册此反序列化器:
@Bean
public Module customStringDeserializer() {
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, CustomStringDeserializer.instance);
return module;
}
当发送一个整数并且期望使用String时,这是错误:
{“timestamp”:”2019-04-24T15:15:58.968+0000″,”status”:400,”error”:”Bad
Request”,”message”:”JSON parse error: Cannot deserialize instance ofjava.lang.String
out of VALUE_NUMBER_INT token; nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize instance ofjava.lang.String
out of VALUE_NUMBER_INT
token\n at [Source: (PushbackInputStream); line: 3, column: 13]
(through reference chain:
org.hello.model.Student[\”age\”])”,”path”:”/hello/echo”}