2017-06-04 68 views
0

我有一个这样的东西作为一个JSON,并需要将其转换为杰克逊的Java用户实例。杰克逊序列化与类型混合?

"userid" : "1", 
"myMixes" : [ { 
    "data" : { 
     "id" : 1, 
     "ref": "my-Object-instance" 
    }, 
    "type" : "object" 
    }, { 
    "data" : [ [ 0, 1], [ 1, 2 ] ], 
    "type" : "list" 
    }] 

我有这个在我的课“用户”:

// jackson should use this, if type="list" 
    @JsonProperty("data") 
    public List<List<Integer>> data_list = new ArrayList<>(); 

    // jackson should use this, if type="object" 
    @JsonProperty("data") 
    public Data data_object; 

    @JsonProperty("id") 
    public String id; 

    // if type = "object", then jackson should convert json-data-property to Java-Data-Instance 
// if type = "list",then jackson should convert json-data-property to List<List<Integer>> data 
    @JsonProperty("type") 
    public String type; 

我怎么能告诉杰克逊生成JSON数据属性的数据,例如,如果JSON的类型 - 价值属性称为“对象”,并且如果json-type-property的值被称为“list”,则生成List-Instance。

回答

0

您可以编写自己的解串器来检查收到的json的类型属性值。喜欢的东西:

@JsonDeserialize(using = UserDeserializer.class) 
public class UserData { 
    ... 
} 



public class UserDeserializer extends StdDeserializer<Item> { 

public UserDeserializer() { 
    this(null); 
} 

public UserDeserializer(Class<?> vc) { 
    super(vc); 
} 

@Override 
public UserData deserialize(JsonParser jp, DeserializationContext ctxt) 
    throws IOException, JsonProcessingException { 
    JsonNode node = jp.getCodec().readTree(jp); 
    String type = node.get("type"); 
    if(type.equals("object")){ 
    // deserialize object 
    }else if(type.equals("list")){ 
    // deserialize list 
    } 
    return new UserData(...); 
    } 
} 
+0

我的解决方案和你的解决方案有什么不同?你的速度更快吗? – nimo23

1

我想,我找到了最好的解决办法:

@JsonCreator 
    public MyMixes(Map<String,Object> props) 
    { 
     ... 

     ObjectMapper mapper = new ObjectMapper(); 

     if(this.type.equals("object")){ 

      this.data_object = mapper.convertValue(props.get("data"), Data.class); 
     } 
     else{ 
      this.data = mapper.convertValue(props.get("data"), new TypeReference<List<List<Integer>>>() { }); 
     } 

    } 

如果某人有一个较短/更快的方法,然后让我知道。