将Map序列化为父对象的属性。

huangapple go评论76阅读模式
英文:

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&lt;String, Object&gt; map;

  publicParent(int propA, String propB, Map&lt;String, Object&gt; map) {
    this.propA = propA;
    this.propB = propB;
    this.map = map;
  }

  public int getPropA() {
    return propA;
  }

  public String getPropB() {
    return propB;
  }

  public Map&lt;String, Object&gt; getMap() {
    return map;
  }

}

When serializing that I'll for instance get this:

{
  &quot;propA&quot;: 5,
  &quot;propB&quot;: &quot;foo&quot;,
  &quot;map&quot;: {
    &quot;bar&quot;: &quot;bong&quot;,
    &quot;bing&quot;: &quot;bang&quot;
  }
}

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?

{
  &quot;propA&quot;: 5,
  &quot;propB&quot;: &quot;foo&quot;,
  &quot;bar&quot;: &quot;bong&quot;,
  &quot;bing&quot;: &quot;bang&quot;
}

答案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&lt;String, Object&gt; getMap() {
    return map;
  }

Here's a helpful guide: https://www.baeldung.com/jackson-annotations

huangapple
  • 本文由 发表于 2020年8月6日 04:07:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63272786.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定