다음과 같은 Json이 있습니다.
{
"testEntities" : [ {
"id" : 1,
"floatNumber" : 0.006117165,
"floatNumberObject" : 0.15273619,
"intNumber" : -1155869325,
"intNumberObject" : 431529176,
"doubleNumber" : 0.41008081149220166,
"doubleNumberObject" : 0.20771484130971707,
"shortNumber" : 9364,
"shortNumberObject" : 13977,
"booleanValue" : true,
"booleanValueObject" : true,
"byteValue" : -79,
"charValue" : "e",
"charValueObject" : "b",
"creationDate" : 86400000
}, {
"id" : 2,
"floatNumber" : 0.9874208,
"floatNumberObject" : 0.45285606,
"intNumber" : -1154715079,
"intNumberObject" : 1260042744,
"doubleNumber" : 0.9014476240300544,
"doubleNumberObject" : 0.49682259343089075,
"shortNumber" : 483,
"shortNumberObject" : 18322,
"booleanValue" : false,
"booleanValueObject" : true,
"byteValue" : -73,
"charValue" : "c",
"charValueObject" : "r",
"creationDate" : 172800000
} ]
}
역 직렬화를 시도하면 다음과 같이 실패합니다.
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Root name 'testEntities' does not match expected ('TestObject[]') for type
이미 배열 역 직렬화를 활성화했습니다.
objectMapper.enable(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY);
분명히 testEntities
Jackson은 아무것도 모르는 사용자 지정 이름입니다. 이 TestObject
클래스에는 JsonRootNamePlural
루트 요소가 단일 인스턴스가 아닌 컬렉션 일 때 사용되는 라는 사용자 지정 주석 이 있습니다.
@JsonRootName("testEntity")
@JsonRootNamePlural("testEntities")
public class TestObject {
...
}
이 주석은 시스템의 다른 위치에서도 필요합니다.
@JsonRootName
배열을 제외하고 주석을 사용하는 것과 동일한 방식으로 사용하고 싶습니다 . 따라서 JsonRootName에 표시된대로 루트 요소를 찾을 수 있으며, 발견되지 않으면 @JsonRootNamePlural을 찾을 수 있습니다. JSON의 다른 모든 루트 이름은 Jackson에서 무시해야합니다.
문제는 이 동작을 도입하기 위해 무엇을 재정의하거나 사용자 정의해야합니까?
어떤 도움이나 조언이라도 대단히 감사합니다!
내 질문에 대한 답을 찾았습니다. 객체 매퍼에 메서드 JacksonAnnotationIntrospector
를 재정의 하는 사용자 지정 인스턴스를 설정 findRootName
해야하며 클래스가 배열인지 확인하고 배열 구성 요소 클래스에서 사용자 지정 주석을 찾습니다.
@Override
public PropertyName findRootName(AnnotatedClass ac) {
// if this is an array, look for JsonRootNamePlural annotation in
// the base type for the array (the so called array component)
if (ac.getRawType().isArray()) {
Class<?> arrayComponent = ac.getRawType().getComponentType();
JsonRootNamePlural ann = arrayComponent.getAnnotation(JsonRootNamePlural.class);
if (ann != null) {
return PropertyName.construct(ann.value(), null);
}
}
// super class will look for default @JsonRootName annotation
return super.findRootName(ac);
}
이것이 다른 사람들을 도울 수 있기를 바랍니다.
건배!
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다