检查它是否适合你。
我已经为属性 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();
}
}
AddConfigInput.java
对于使用自定义反序列化器的 refId 属性。
package oct2020.json;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class AddConfigInput {
public String channel;
public String data;
@JsonDeserialize(using = KeepStringDeserializer.class)
public String refId;
public String description;
public String[] tags;
public AddConfigInput() {
}
}
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));
}
}
输出:
案例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"]}