Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Inlining" an object with Jackson Annotations

Tags:

java

json

jackson

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.

like image 788
Tomas Aschan Avatar asked Sep 01 '25 10:09

Tomas Aschan


1 Answers

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.

like image 178
ernest_k Avatar answered Sep 02 '25 23:09

ernest_k