2017-11-13 7 views
2

나는 spring restTemplate을 사용하여 POJO에 응답을 매핑합니다. 나머지 API의 응답은 다음과 같이이다 : 부모 클래스에서spring restTemplate 동적 매핑

"attributes": { 
    "name": { 
     "type": "String", 
     "value": ["John Doe"] 
    }, 
    "permanentResidence": { 
     "type": "Boolean", 
     "value": [true] 
    }, 
    "assignments": { 
     "type": "Grid", 
     "value": [{ 
      "id": "AIS002", 
      "startDate": "12012016", 
      "endDate": "23112016" 
     },{ 
      "id": "AIS097", 
      "startDate": "12042017", 
      "endDate": "23092017" 
     }] 
    } 
} 

, 내가 가진 :

public class Users { 
    private Map<String, Attribute> attributes; 
} 

했다 문자열 유형의 모든 값은, 그때처럼 할 수 있었던 경우

public class Attribute { 
    private String type; 
    private String[] value; 
} 

그러나 값은 다른 유형입니다. 그래서 다음과 같은 생각 :

public class Attribute { 
    private String type; 
    private Object[] value; 
} 

위의 작업을해야하지만 모든 단계에서 나는 어떤 종류의 개체인지 알아야합니다.
그래서, 내 질문은 내가 이런 걸 할 수있다 :

public class Attribute { 

    @JsonProperty("type") 
    private String type; 

    @JsonProperty("value") 
    private String[] stringValues; 

    @JsonProperty("value") 
    private Boolean[] booleanValues; 

    @JsonProperty("value") 
    private Assignments[] assignmentValues; // for Grid type 
} 

을하지만 작업 및 오류를 던지고되지 않습니다 Conflicting setter definitions for property "value"

이 시나리오를 처리 권장되는 방법은 무엇입니까?

여기 다형성을 처리하기 위해 잭슨 시설을 추천 할 것입니다

답변

1

:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type") 
@JsonSubTypes({ 
     @JsonSubTypes.Type(value = BooleanAttribute.class, name = "Boolean"), 
     @JsonSubTypes.Type(value = StringAttribute.class, name = "String") 
}) 
class Attribute { 
    private String type; 
} 

class BooleanAttribute extends Attribute { 
    private Boolean[] value; 
} 

class StringAttribute extends Attribute { 
    private String[] value; 
} 

JsonTypeInfo이 기본 클래스이고 유형이라는 JSON 필드에 의해 결정됩니다 잭슨을 알려줍니다 "type"

JsonSubTypes지도 아형 Attribute과 JSON의 "type"

Assignments 및 getters/setters에 적절한 하위 유형을 추가하면 Jackson이 JSON을 구문 분석 할 수 있습니다.