英文:
Serialize Map as properties of parent object
问题
你可以使用@JsonAnyGetter
注解来实现这个目标。在你的Parent
类中添加以下注解:
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Parent {
private final int propA;
private final String propB;
private final Map<String, Object> map;
public Parent(int propA, String propB, Map<String, Object> map) {
this.propA = propA;
this.propB = propB;
this.map = map;
}
public int getPropA() {
return propA;
}
public String getPropB() {
return propB;
}
@JsonAnyGetter
public Map<String, Object> getMap() {
return map;
}
}
这将告诉Jackson将map
的所有条目作为Parent
对象的属性进行序列化,得到你期望的输出。
英文:
I have a class Parent which has some properties including one Map<String, object>.
public class Parent {
private final int propA;
private final String propB;
private final Map<String, Object> map;
publicParent(int propA, String propB, Map<String, Object> map) {
this.propA = propA;
this.propB = propB;
this.map = map;
}
public int getPropA() {
return propA;
}
public String getPropB() {
return propB;
}
public Map<String, Object> getMap() {
return map;
}
}
When serializing that I'll for instance get this:
{
"propA": 5,
"propB": "foo",
"map": {
"bar": "bong",
"bing": "bang"
}
}
How can I annotate the class so Jackson will serialize an instance of it placing the map entries as bare properties to the parent object instead?
{
"propA": 5,
"propB": "foo",
"bar": "bong",
"bing": "bang"
}
答案1
得分: 1
我已使用@JsonAnyGetter
注解来实现此功能。还有一个匹配的@JsonAnySetter
注解,它的作用相反:将无法识别的属性放入一个映射中。
@JsonAnyGetter
public Map<String, Object> getMap() {
return map;
}
这里有一个有用的指南:https://www.baeldung.com/jackson-annotations
英文:
I've used the @JsonAnyGetter
annotation to achieve this. There is also a matching @JsonAnySetter
annotation that does the opposite: stuff unrecognized properties in a map.
@JsonAnyGetter
public Map<String, Object> getMap() {
return map;
}
Here's a helpful guide: https://www.baeldung.com/jackson-annotations
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论