问题描述
我有以下JSON:
{
fields : {
"foo" : "foovalue",
"bar" : "barvalue"
}
}
我写了一个pojo如下:
I wrote a pojo as follows :
public class MyPojo {
@JsonProperty("fields")
private List<Field> fields;
static class Field {
@JsonProperty("foo") private String foo;
@JsonProperty("bar") private String bar;
//Getters and setters for those 2
}
这显然失败了,因为我的json字段fields是一个hashmap,而不是一个列表。
我的问题是:是否有任何魔术注释可以让Jackson将地图键识别为pojo属性名称,并将地图值分配给pojo属性值?
This fails obviously, because my json field "fields" is a hashmap, and not a list.
My question is : is there any "magic" annotation that can make Jackson recognize the map keys as pojo property names, and assign the map values to the pojo property values ?
PS:我真的不希望我的字段对象为...
P.S.: I really don't want to have my fields object as a...
private Map<String, String> fields;
...因为在我的真实世界json中我在地图值中有复杂的对象,而不仅仅是字符串......
...because in my real-world json I have complex objects in the map values, not just strings...
谢谢; - )
Philippe
推荐答案
好的,对于那个JSON,您只需稍微修改一下您的示例,例如:
Ok, for that JSON, you would just modify your example slightly, like:
public class MyPojo {
public Fields fields;
}
public class Fields {
public String foo;
public String bar;
}
因为对象的结构需要与JSON的结构对齐。你当然可以使用setter和getter而不是public字段(甚至是构造函数而不是setter或fields),这只是最简单的例子。
since structure of objects needs to align with structure of JSON. You could use setters and getters instead of public fields of course (and even constructors instead of setters or fields), this is just the simplest example.
你的原始类会产生/消耗JSON更像:
Your original class would produce/consume JSON more like:
{
"fields" : [
{
"foo" : "foovalue",
"bar" : "barvalue"
}
]
}
因为列表映射到JSON数组。
because Lists map to JSON arrays.
这篇关于如何使用Jackson注释序列化此JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!