あなたはgetPathReferenceに主にある、getPathとを使用してJsonMappingExceptionクラスと(com.fasterxml.jackson.databind.excパッケージの下)そのサブクラスのうち、例外のうち、方法をいくつかの貴重な情報を得ることができ
はここで2つの例です:
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が例外をスローしなかった場合、なぜそれは有効ではないはずですか?ビジネス検証ですか? –
年齢はEmployeeクラスのプロパティで、私はこのプロパティに文字列値を割り当てました。オブジェクトがjsonから例外を使用して準備されていますが、この例外から、従業員のどのプロパティがエラーを起こしやすいか理解できません –
使用しているjacksonとspringのバージョン –