2017-07-07 56 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