2017-11-13 43 views
2

私は、応答をPOJOにマップするためにspring restTemplateを使用しています。残りのAPIの 応答はこのようなものです:親クラスでspring restテンプレートの動的マッピング

"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これは基底クラスで、タイプは"type"

JsonSubTypesマップサブタイプという名前のJSONフィールドによって決定されることをジャクソンに伝えますAttributeの値をJSONの"type"に設定します。

Assignmentsとgetters/settersに適切なサブタイプを追加すると、JacksonはJSONを解析できます。

関連する問題