2016-08-23 54 views
1

我接收它們都具有字段內容對象的JSON陣列亞型,但該字段的類型可能會有所不同:和解組JSON到具有不同字段類型傑克遜

[ 
    { 
     "id": "primaryBodyHeader", 
     "type": "RichText", 
     "content": "<h1>Alice's Adventures in Wonderland</h1>" 
    }, 
    { 
     "id": "1027", 
     "type": "RichText", 
     "content": { 
      "value": "RVMtMTk=", 
      "contentType": "DynamicContent" 
     } 
    } 
] 

和我有豆:

public abstract class LandingPageContentItem { 
    private String id; 
    private String type; 
    private String content; 
} 

至少我要地圖內容文本字段時,它是一個文本(空非文本內容)

我想根據字段類型內容 - TextContentItem,ComplexContentItem等等,將不同類型的項目映射到不同的子類。 @JsonSubTypes不能這樣做

有沒有辦法做到這一點沒有自定義的反序列化器?

回答

2

如果你不知道(或者沒有控制)可能是什麼在content場,那麼我建議你生com.fasterxml.jackson.databind.JsonNode映射這樣

public static class LandingPageContentItem { 
    private final String id; 
    private final String type; 
    private final JsonNode content; 

    @JsonCreator 
    public LandingPageContentItem(
      @JsonProperty("id") final String id, 
      @JsonProperty("type") final String type, 
      @JsonProperty("content") final JsonNode content) { 
     this.id = id; 
     this.type = type; 
     this.content = content; 
    } 

    /* some logic here */ 
} 

然後你就可以正常讀取它

ObjectMapper mapper = new ObjectMapper(); 
List<LandingPageContentItem> items = 
    mapper.readValue(node, new TypeReference<List<LandingPageContentItem>>() {}); 

稍後,您可以驗證JsonNode是否爲預期類型。

if (content.isTextual()) { 
    // do something with content.asText(); 
} 
2

無需編寫自定義的解串器,我能想到的最好的是:

public class LandingPageContentItem { 
    private String id; 
    private String type; 
    private Object content; 
} 

然後,只需使用if(item.content instanceof String)if(item.content instanceof Map)從那裏處理它。

+0

@vsminkov有更好的答案。在大多數情況下,'JsonNode'可能比'Object'更好。 –