假设我有以下对象。
class Foo {
private String name;
private int age;
private Map<String, object> extra;
}
public static void main(String[] args) {
Foo foo = new Foo();
foo.name = "adam";
foo.age = 25;
foo.extra.put("hobbies", /** list of hobbies **/)
foo.extra.put("firends", /** list of friends **/)
// convert to json...
}
我想要以下输出...是否可以通过使用自定义序列化来做到这一点?
{
"name": "adam",
"age": 25,
"hobbies": [
{
"name": "footbal",
"level": 1
}
{
"name": "coding",
"level": 2
}
],
"friends": [
{
"id": 1
"name": "jack"
},
{
"id": 2
"name": "rose"
}
]
}
最佳答案
我找到了实现的方法。通过对 Map 使用 @JsonIgnore
@JsonAnyGetter
的组合,但如果您只有自定义对象,则只能使用 @JsonUnwrapped
来获得相同的结果行为。
class Foo {
private String name;
private int age;
@JsonIgnore
private Map<String, Object> extra;
@JsonAnyGetter
public Map<String, Object> getExtra() {
return extra;
}
}
关于java - Jackson 将 Map 合并到 json 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57946324/