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:
{
"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?
{
"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:
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.
Your Bar
class would look like this:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With