2017-06-04 54 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>>>() { }); 
     } 

    } 

如果某人有一個較短/更快的方法,然後讓我知道。