Java 如何使用 Jackson 注释序列化此 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4410470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I serialize this JSON using Hymanson annotations?
提问by Philippe
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.
My question is : is there any "magic" annotation that can make Hymanson recognize the map keys as pojo property names, and assign the map values to the pojo property values ?
这显然失败了,因为我的 json 字段“字段”是一个哈希图,而不是一个列表。
我的问题是:是否有任何“魔法”注释可以让Hyman逊将地图键识别为 pojo 属性名称,并将地图值分配给 pojo 属性值?
P.S.: 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
菲利普
采纳答案by StaxMan
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. 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 的结构保持一致。当然,您可以使用 setter 和 getter 代替公共字段(甚至可以使用构造函数代替 setter 或字段),这只是最简单的示例。
Your original class would produce/consume JSON more like:
您的原始类将更像生成/使用 JSON:
{
"fields" : [
{
"foo" : "foovalue",
"bar" : "barvalue"
}
]
}
because Lists map to JSON arrays.
因为列表映射到 JSON 数组。