你可以得到一些有價值的信息出來的異常主要是出於使用的getPath和JsonMappingException類和它的子類(在com.fasterxml.jackson.databind.exc包下)的getPathReference方法
下面是兩個例子:
public class ObjectMapperTest {
private ObjectMapper objectMapper;
@Before
public void setup() {
objectMapper = new ObjectMapper();
}
@Test
public void testWrongDataType() {
String personStr = "{\"age\":\"100Y\",\"firstName\":\"Jackson\",\"lastName\":\"Pollock\",\"gender\":\"M\"}";
try {
objectMapper.readValue(personStr, Person.class);
} catch (JsonMappingException jme) {
System.out.println(jme.getMessage());
if(jme instanceof InvalidFormatException) {
InvalidFormatException ife = (InvalidFormatException)jme;
System.out.println("Mapping failure on field:" + ife.getPathReference());
System.out.println("Expected type: " + ife.getTargetType());
System.out.println("provided value: " + ife.getValue());
}
}catch (Exception e){
System.out.println(e.getMessage());
}
}
@Test
public void testUnrecognizedProperty() {
String personStr = "{\"gae\":\"100\",\"firstName\":\"Jackson\",\"lastName\":\"Pollock\",\"gender\":\"M\"}";
try {
objectMapper.readValue(personStr, Person.class);
} catch (JsonMappingException jme) {
System.out.println(jme.getMessage());
if(jme instanceof PropertyBindingException) {
PropertyBindingException pbe = (PropertyBindingException) jme;
System.out.println("Mapping failure on field:" + pbe.getPathReference());
System.out.println("UnExpected field: " + pbe.getPropertyName());
}
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
的輸出將是
testUnrecognizedProperty:
========================
Unrecognized field "gae" (class Person), not marked as ignorable (4 known properties: "lastName", "gender", "firstName", "age"])
at [Source: {"gae":"100","firstName":"Jackson","lastName":"Pollock","gender":"M"}; line: 1, column: 9] (through reference chain: Person["gae"])
Mapping failure on field:Person["gae"]
UnExpected field: gae
testWrongDataType:
========================
Can not construct instance of java.lang.Integer from String value '100Y': not a valid Integer value
at [Source: {"age":"100Y","firstName":"Jackson","lastName":"Pollock","gender":"M"}; line: 1, column: 2] (through reference chain: Person["age"])
Mapping failure on field:Person["age"]
Expected type: class java.lang.Integer
provided value: 100Y
我不確定我是否完全理解用例。我認爲employeeMap是僱用值。那麼爲什麼它不應該是有效的,如果writeValueAsString沒有拋出任何異常?你的意思是業務驗證? –
假設age是Employee類的一個屬性,並且我給這個屬性賦了一個字符串值。當從json準備對象時,它通過異常但是從這個異常我無法理解員工的哪個屬性容易出錯 –
您能指定您正在使用的傑克遜和春季版本 –