[英]“Inlining” an object with Jackson Annotations
With these classes有了这些课
import com.fasterxml.jackson.annotation.JsonProperty;
public class Foo {
@JsonProperty
public String bar;
}
public class Bar {
@JsonProperty
public Foo foo;
@JsonProperty {
public String baz;
}
I can serialize and deserialize a Bar
instance to/from JSON objects like this one:我可以像这样从 JSON 对象序列化和反序列化
Bar
实例:
{
"foo": { "bar": "bar" },
"baz": "baz"
}
Is there a Jackson annotation that will let me "inline" the foo
field, so that my JSON representation becomes this?是否有 Jackson 注释可以让我“内联”
foo
字段,以便我的 JSON 表示变成这样?
{
"bar": "bar",
"baz": "baz"
}
I'm totally OK with it throwing errors in case of naming conflicts etc, but it would be nice if I didn't have to implement a custom serializer for this.我完全可以在命名冲突等情况下抛出错误,但如果我不必为此实现自定义序列化程序,那就太好了。
You can use @JsonUnwrapped :您可以使用@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.
也就是说,如果它将被序列化为 JSON 对象,则其属性将作为其包含对象的属性包含在内。
Your Bar
class would look like this:您的
Bar
类将如下所示:
public class Bar {
@JsonUnwrapped
private Foo foo;
@JsonProperty
private String baz;
}
And that produces your desired output.这会产生您想要的输出。 Removing
@JsonProperty
from the field didn't seem to make a difference, so I just omitted it.从字段中删除
@JsonProperty
似乎没有什么区别,所以我只是省略了它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.