我有一个类似于json的东西,需要将它转换为Jackson的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-type-property的值被称为“object”,并且生成List-Instance(如果json-type的值),我怎么能告诉jackson生成json-data-property的数据实例?属性称为“列表”。
答案 0 :(得分: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>>>() { });
}
}
如果某人有更短/更快的方式,请告诉我。
答案 1 :(得分:0)
您可以编写自己的反序列化程序来检查收到的json的type属性值。类似的东西:
@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(...);
}
}