2013-07-01 4 views
4

@JsonProperty()를 사용하여 다른 json 객체 내에서 json 객체를 얻는 방법은 무엇입니까? 내가 싶어 예제 JSON은 다음과 같습니다 생성자에 @JsonProperty 주석을 사용@JsonProperty Json 객체 내부의 Json 객체

"location" : { 
    "needs_recoding" : false, 
    "longitude" : "-94.35281245682333", 
    "latitude" : "35.35363522126198", 
    "human_address" : "{\"address\":\"7301 ROGERS AVE\",\"city\":\"FORT SMITH\",\"state\":\"AR\",\"zip\":\"\"}" 
} 
+0

어디에서 코드를 사용할 수 있습니까? 어노테이션이 필요 없으며 속성에서 적절한 빈 참조 만 필요합니다. –

+0

생성자에서 사용하고 있습니다 – Hank

답변

2

A helpful referenceStaxMan에 의해 제공됩니다. 아래에 표시된 간단한 예는 다음과 같습니다.

public class Address { 
    private String address; 
    private String city; 
    private String state; 
    private String zip; 

    // Constructors, getters/setters 
} 

public class Location { 
    private boolean needsRecoding; 
    private Double longitude; 
    private Double latitude; 
    private Address humanAddress; 

    public Location() { 
     super(); 
    } 

    @JsonCreator 
    public Location(
     @JsonProperty("needs_recoding") boolean needsRecoding, 
     @JsonProperty("longitude") Double longitude, 
     @JsonProperty("latitude") Double latitude, 
     @JsonProperty("human_address") Address humanAddress) { 

     super(); 
     this.needsRecoding = needsRecoding; 
     this.longitude = longitude; 
     this.latitude = latitude; 
     this.humanAddress = humanAddress; 
    } 

    // getters/setters 
} 

또는 JSON 개체 트리에 직접 내용을 역 직렬화 할 수 있습니다. Location 클래스의 예를 약간 수정하여 아래에 설명되어 있습니다.

public class Location { 
    private boolean needsRecoding; 
    private Double longitude; 
    private Double latitude; 

    // Note the use of JsonNode, as opposed to an explicitly created POJO 
    private JsonNode humanAddress; 

    public Location() { 
     super(); 
    } 

    @JsonCreator 
    public Location(
     @JsonProperty("needs_recoding") boolean needsRecoding, 
     @JsonProperty("longitude") Double longitude, 
     @JsonProperty("latitude") Double latitude, 
     @JsonProperty("human_address") JsonNode humanAddress) { 

     super(); 
     this.needsRecoding = needsRecoding; 
     this.longitude = longitude; 
     this.latitude = latitude; 
     this.humanAddress = humanAddress; 
    } 

    // getters/setters 
} 
+0

위치 클래스를 만들지 않고 위치에 포함 된 Json 객체를 가져올 방법이 없습니까? – Hank

+0

@ Hank - 데이터를 ['JsonNode'] (http://fasterxml.github.io/jackson-databind/javadoc/2.0.2/com/fasterxml/jackson/databind/JsonNode.html)로 직접 deserialize 할 수 있습니다. 예를 들어 내 답변 편집을 참조하십시오. – Perception