"Inlining" 带有 Jackson 注释的对象

"Inlining" an object with Jackson Annotations

有了这些类

import com.fasterxml.jackson.annotation.JsonProperty;

public class Foo {
    @JsonProperty
    public String bar;
}

public class Bar {
    @JsonProperty
    public Foo foo;

    @JsonProperty {
    public String baz;
}

我可以序列化和反序列化一个 Bar 实例 to/from JSON 像这样的对象:

{
  "foo": { "bar": "bar" },
  "baz": "baz"
}

是否有 Jackson 注释可以让我“内联”foo 字段,以便我的 JSON 表示变成这样?

{
  "bar": "bar",
  "baz": "baz"
}

我完全同意它在命名冲突等情况下抛出错误,但如果我不必为此实现自定义序列化程序就好了。

您可以使用 @JsonUnwrapped:

Annotation used to indicate that a property should be serialized "unwrapped"; that is, if it would be serialized as JSON Object, its properties are instead included as properties of its containing Object.

您的 Bar class 将如下所示:

public class Bar {
    @JsonUnwrapped
    private Foo foo;

    @JsonProperty
    private String baz;
}

这会产生您想要的输出。从字段中删除 @JsonProperty 似乎没有什么不同,所以我只是省略了它。