英文:
Mapping the different type of values for one field in JSON to java object using Jackson
问题
{
"firstname": "first_name",
"age": "34",
"add_info": [{
"type": "type_a",
"value": "value_a"
},
{
"type": "type_b",
"value": [{
"title": "info_1",
"desc": "desc_1"
},
{
"title": "info_2",
"desc": "desc_2"
}
]
}
]
}
POJO: 基本上,使用此POJO,我不知道如何定义它
public class AddInfo {
private String type;
private List
//getter and setters
}
在上面的JSON中,add_info字段包含一个JSON对象数组,在其中第一个对象的值是字符串类型,第二个值包含一个对象数组。
如何在Pojo中使用jackson处理这种情况
英文:
We have a json where for a particular field the data type is different. I want to map it to Java Object using jackson. If the fields are of one type i am able to do it. but for different type unable to find a way.
{
"firstname": "first_name",
"age": "34",
"add_info": [{
"type": "type_a",
"value": "value_a"
},
{
"type": "type_b",
"value": [{
"title": "info_1",
"desc": "desc_1"
},
{
"title": "info_2",
"desc": "desc_2"
}
]
}
]
}
POJO: Basically with this POJO i dont know how to define it
public class AddInfo {
private String type;
private List<Value> value = null;
//getter and setters
}
In the above JSON for add_info field it contains array of JSON object wherein first object value is of type string and second value holds an array of object.
How to handle this kind of situation in Pojo using jackson
答案1
得分: 1
如果您不想编写自定义反序列化器,您可以简单地使用一个Object字段:
public class AddInfo {
public String type;
public Object value;
public static void main(String[] args) throws Exception {
ObjectMapper om = new ObjectMapper();
AddInfo i1 = om.readValue("{\"value\":\"string\"}", AddInfo.class);
System.out.println(i1.value);
AddInfo i2 = om.readValue("{\"value\":[{\"x\":1}]}", AddInfo.class);
System.out.println(i2.value);
}
}
在第一次运行时,i1.value是一个字符串。在第二次运行时,i2.value是一个哈希映射列表。
所以你失去了Pojo结构。
英文:
If you do not want to write a custom deserializer, you could simply use an Object field:
public class AddInfo {
public String type;
public Object value;
public static void main(String[] args) throws Exception {
ObjectMapper om = new ObjectMapper();
AddInfo i1 = om.readValue("{\"value\":\"string\"}", AddInfo.class);
System.out.println(i1.value);
AddInfo i2 = om.readValue("{\"value\":[{\"x\":1}]}", AddInfo.class);
System.out.println(i2.value);
}
}
In the first run, i1.value is a String. In the second run, i2.value is a list of hashmaps.
So you loose the Pojo structure.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论