2011-12-06 2 views
2

Jackson은 @JsonProperty 주석 값 (즉, JSON 속성 키)을 콩 필드 이름으로 반환하는 도우미 메서드가 있습니까?Jackson JSON의 @JsonProperty 매핑을위한 도우미 메서드

상황 :

나는 콩으로 클라이언트가 제공하는 JSON 변환 잭슨을 사용하여 다음 빈을 검증하기 위해 JSR-303을 사용하고 있습니다. 유효성 검사가 실패하면 클라이언트에게 의미있는 오류 메시지를 다시보고해야합니다. 유효성 검증 오브젝트는 bean 특성을 참조합니다. 오류 메시지는 JSON 속성을 참조해야합니다. 따라서 하나에서 다른 하나로 매핑 할 필요가 있습니다.

답변

3

당신은, BeanDescription 객체를 통해 정보의 조금을 확실히 얻을 수있다. 그러나이 기능은 몇 개의 Jackson 확장 모듈에서 사용되므로 지원되는 유스 케이스입니다. 그래서 : 필요한 경우

ObjectMapper mapper = ...; 
JavaType type = mapper.constructType(PojoType.class); // JavaType to allow for generics 
// use SerializationConfig to know setup for serialization, DeserializationConfig for deser 
BeanDescription desc = mapper.getSerializationConfig().introspect(type); 

당신은 또한 안전하게 BasicBeanDescription로 업 캐스팅 할 수 있습니다.

이렇게하면 많은 정보에 액세스 할 수 있습니다. (이를 통해 getter/setter/field/ctor-argument를 찾을 수있는) 논리적 속성 목록, 완전히 해석 된 메소드 (주석 포함) 등이 있습니다. 그렇게 잘하면 충분합니다. 논리 속성은 외부 이름 (JSON에서 예상되는 이름)과 getter/setter에서 파생 된 내부 이름을 모두 포함하므로 유용합니다.

0

나는 이것을 특히 쉽게 만들기 위해 잭슨에서 어떤 것도 알지 못합니다. 반사 기반 솔루션이면 충분할 수 있습니다. 하나를 점점 꽤 까다 롭습니다하지만 (이 대부분 잭슨의 내부 사용을 위해 설계 대부분 때문에)

import java.lang.reflect.Field; 

import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; 
import org.codehaus.jackson.annotate.JsonMethod; 
import org.codehaus.jackson.annotate.JsonProperty; 
import org.codehaus.jackson.map.ObjectMapper; 

public class JacksonFoo 
{ 
    public static void main(String[] args) throws Exception 
    { 
    // {"$food":"Green Eggs and Ham"} 
    String jsonInput = "{\"$food\":\"Green Eggs and Ham\"}"; 

    ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY); 
    Bar bar = mapper.readValue(jsonInput, Bar.class); 

    new Jsr303().validate(bar); 
    // output: 
    // I do not like $food=Green Eggs and Ham 
    } 
} 

class Bar 
{ 
    @JsonProperty("$food") 
    String food; 
} 

class Jsr303 
{ 
    void validate(Bar bar) throws Exception 
    { 
    Field field = Bar.class.getDeclaredField("food"); 
    JsonProperty annotation = field.getAnnotation(JsonProperty.class); 
    System.out.printf("I do not like %s=%s", annotation.value(), bar.food); 
    } 
}