2017-07-07 62 views
1

我有幾個的Json字符串如下:傑克遜多態性 - 抽象類,沒有財產

{"type1": {"name": "Arnold"}} 
{"type2": {"id": "abcd", "job": "plumber"}} 

我想是一個JSON字符串轉換爲根據Type1Type2類之一,最終的事元素的root屬性:

// Type0 abstract class 
public abstract class Type0 { 
} 

// Type1 class.. convert to it if {"type1": {...}} 
@JsonRootName(value = "type1") 
public class Type1 extends Type0 { 
    @JsonProperty("name") 
    String name; 
} 

// Type2 class.. convert to it if {"type2": {...}} 
@JsonRootName(value = "type2") 
public class Type2 extends Type0 { 
    @JsonProperty("id") 
    String id; 

    @JsonProperty("job") 
    String job; 
} 

如何配置傑克遜的ObjectMapper,這樣我可以做到這一點反序列化?我認爲一個邏輯的像如下,它是可行的:

ObjectMapper mapper = new ObjectMapper(); 
result = mapper.readValue(jsonString, Type0.class); 
//TODO: code for deciding whether result is Type1 or Type2 and casting to it 

回答

1

傑克遜支持具有WRAPPER_OBJECT這樣的情況。與readValue解析Type0.class

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) 
@JsonSubTypes({ 
     @JsonSubTypes.Type(name = "type1", value = Type1.class), 
     @JsonSubTypes.Type(name = "type2", value = Type2.class)}) 
abstract class Type0 {} 

,然後你會得到相應的派生類的一個實例:註釋抽象類是這樣的。您不需要派生類上的@JsonRootName