将JSON中一个字段的不同类型值映射到Java对象,使用Jackson。

huangapple go评论62阅读模式
英文:

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 value = null;
//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.

huangapple
  • 本文由 发表于 2020年8月8日 03:42:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63308269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定