Java 如何指示Jackson ObjectMapper不将数字字段值转换为字符串属性?

Java 如何指示Jackson ObjectMapper不将数字字段值转换为字符串属性?,java,json,jackson,jackson-databind,Java,Json,Jackson,Jackson Databind,我有以下JSON示例: { "channel": "VTEX", "data": "{}", "refId": 143433.344, "description": "teste", "tags": ["tag1", "tag2"] } 应映射到以下类: p

我有以下JSON示例:

{
    "channel": "VTEX",
    "data": "{}",
    "refId": 143433.344,
    "description": "teste",
    "tags": ["tag1", "tag2"]
}
应映射到以下类:

public class AddConfigInput {
    public String channel;
    public String data;
    public String refId;
    public String description;
    public String[] tags;

    public AddConfigInput() {
    }
}
使用如下代码:

ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS);
String json = STRING_CONTAINING_THE_PREVIOUS_INFORMED_JSON;
AddConfigInput obj = mapper.readValue(json, AddConfigInput.class);
System.out.println(mapper.writeValueAsString(obj));
作为输出产生:

{"channel":"VTEX","data":"{}","refId":"143433.344","description":"teste","tags":["tag1","tag2"]}

请注意,refId字段的类型为String,我希望避免这种从数字到字符串属性的自动转换。相反,我希望Jackson抛出一个关于类型不匹配的错误。我该怎么做?

检查它是否适合您

我为属性refId添加了一个自定义反序列化程序,在那里我检查类型,以防出现数据类型不匹配引发异常

用于强制数据类型检查的自定义反序列化程序

KeepStringDeserializer.java

package oct2020.json;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

public class KeepStringDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jsonParser,
            DeserializationContext deserializationContext) throws IOException {
        if (jsonParser.getCurrentToken() != JsonToken.VALUE_STRING) {
            throw deserializationContext.wrongTokenException(jsonParser,
                    String.class, JsonToken.VALUE_STRING,
                    "Expected value is string but other datatype found.");
        }
        return jsonParser.getValueAsString();
    }
}
TestClient.java

package oct2020.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestClient {
    public static void main(String[] args) throws JsonMappingException,
            JsonProcessingException {
        String json = "{\n    \"channel\": \"VTEX\",\n    \"data\": \"{}\",\n    \"refId\": 143433.344,\n    \"description\": \"teste\",\n    \"tags\": [\"tag1\", \"tag2\"]\n}\"";
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS);
        AddConfigInput obj = mapper.readValue(json, AddConfigInput.class);
        System.out.println(mapper.writeValueAsString(obj));
    }
}
输出:

{"channel":"VTEX","data":"{}","refId":"143433.344","description":"teste","tags":["tag1","tag2"]}
案例1:数据不匹配

Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (VALUE_NUMBER_FLOAT), Expected value is string but other datatype found.
 at [Source: (String)"{
    "channel": "VTEX",
    "data": "{}",
    "refId": 143433.344,
    "description": "teste",
    "tags": ["tag1", "tag2"]
}""; line: 4, column: 14] (through reference chain: oct2020.json.AddConfigInput["refId"])
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
案例2:正确的数据

输入:

String json = "{\n    \"channel\": \"VTEX\",\n    \"data\": \"{}\",\n    \"refId\": \"143433.344\",\n    \"description\": \"teste\",\n    \"tags\": [\"tag1\", \"tag2\"]\n}\"";
输出:

{"channel":"VTEX","data":"{}","refId":"143433.344","description":"teste","tags":["tag1","tag2"]}

似乎
mapper.disable(MapperFeature.ALLOW\u强制\u标量)
适用于相反的情况,也就是说,将
字符串
值反序列化为数值字段时解析失败

refId
字段提供自定义反序列化程序似乎可以解决此问题

公共类AddConfigInput{
公共字符串频道;
公共字符串数据;
//@JsonDeserialize(使用=ForceStringDeserializer.class)
公共字符串refId;
公共字符串描述;
公共字符串[]标记;
公共AddConfigInput(){
}
}
然后可以使用
ObjectMapper
注册此模块:

mapper.registerModule(new ForcedStringParserModule ());
稍微修改输入JSON后(使用布尔值表示
数据
字段,该字段必须为字符串),将引发以下异常:

Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: 
Unexpected token (VALUE_FALSE), expected VALUE_STRING: 
Attempted to parse token VALUE_FALSE to string
 at [Source: (String)"{
    "channel": "VTEX",
    "data": false,
    "refId": "143433.344",
    "description": "teste",
    "tags": ["tag1", "tag2"]
}"; line: 3, column: 13]

因此,您希望Jackson将
字符串
字段反序列化为双精度字段吗?@AlexRudenko Jackson正在将143433.344(JSON中的数字)转换为Java类中的字符串属性refId“143433.344”,但我希望Jackson抛出一个类型不匹配错误。是的,它是有效的!非常感谢。但是,我希望此验证是我应用程序中每个字符串字段的默认验证。有什么方法可以使KeepStringDeserializer成为字符串字段的默认值吗?@tonyfarney,这是可能的,但是它会影响所有字符串的解析。这就是我要找的!非常感谢。
Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: 
Unexpected token (VALUE_FALSE), expected VALUE_STRING: 
Attempted to parse token VALUE_FALSE to string
 at [Source: (String)"{
    "channel": "VTEX",
    "data": false,
    "refId": "143433.344",
    "description": "teste",
    "tags": ["tag1", "tag2"]
}"; line: 3, column: 13]