[英]How can I serialize this JSON using Jackson annotations?
I have the following JSON : 我有以下JSON:
{
fields : {
"foo" : "foovalue",
"bar" : "barvalue"
}
}
I wrote a pojo as follows : 我写了一个pojo如下:
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
}
This fails obviously, because my json field "fields" is a hashmap, and not a list. 这显然会失败,因为我的json字段“fields”是一个hashmap,而不是一个列表。
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 ? 我的问题是:是否有任何“魔术”注释可以使杰克逊将地图键识别为pojo属性名称,并将地图值分配给pojo属性值?
PS: I really don't want to have my fields object as a... PS:我真的不想让我的田野对象......
private Map<String, String> fields;
...because in my real-world json I have complex objects in the map values, not just strings... ...因为在我的真实世界json中,我在地图值中有复杂的对象,而不仅仅是字符串......
Thanks ;-) 谢谢 ;-)
Philippe 菲利普
Ok, for that JSON, you would just modify your example slightly, like: 好的,对于那个JSON,你只需稍微修改你的例子,如:
public class MyPojo {
public Fields fields;
}
public class Fields {
public String foo;
public String bar;
}
since structure of objects needs to align with structure of JSON. 因为对象的结构需要与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.
你当然可以使用setter和getter而不是public字段(甚至是构造函数而不是setter或fields),这只是最简单的例子。
Your original class would produce/consume JSON more like: 您的原始类将生成/使用JSON更像:
{
"fields" : [
{
"foo" : "foovalue",
"bar" : "barvalue"
}
]
}
because Lists map to JSON arrays. 因为列表映射到JSON数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.