如何使用 Jackson 注释序列化此 JSON?
我有以下 JSON:
{
fields : {
"foo" : "foovalue",
"bar" : "barvalue"
}
}
我编写了一个 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
}
这显然失败了,因为我的 json 字段“fields”是一个哈希图,而不是一个列表。
我的问题是:是否有任何“神奇”注释可以使 Jackson 将映射键识别为 pojo 属性名称,并将映射值分配给 pojo 属性值?
PS:我真的不想让我的 fields 对象作为...
private Map<String, String> fields;
...因为在我的现实世界 json 中,我在地图值中有复杂的对象,而不仅仅是字符串...
谢谢;-)
Philippe
I have the following JSON :
{
fields : {
"foo" : "foovalue",
"bar" : "barvalue"
}
}
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
}
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 ?
P.S.: I really don't want to have my fields object as a...
private Map<String, String> fields;
...because in my real-world json I have complex objects in the map values, not just strings...
Thanks ;-)
Philippe
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,对于该 JSON,您只需稍微修改您的示例,例如:
因为对象的结构需要与 JSON 的结构保持一致。当然,您可以使用 setter 和 getter 来代替公共字段(甚至可以使用构造函数来代替 setter 或字段),这只是最简单的示例。
您的原始类将生成/使用 JSON 更像:
因为列表映射到 JSON 数组。
Ok, for that JSON, you would just modify your example slightly, like:
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.
Your original class would produce/consume JSON more like:
because Lists map to JSON arrays.