Radu Ionescu
Radu Ionescu

Reputation: 3532

Jackson serialize the child class as fields in parent class

I am trying to obtain the following effect.

class Foo{
    public Bar bar;
    public int f1 = 1;
}

public class Bar{
    public int b1;
    public int b2;
}

If you serialize this to JSON you will get

{ "bar" : {
              "b1" : 1,
              "b2" : 2,
          },
   "f1" : 0
}

But I am loking on the Jackson annotations to have it written as

{  
   "b1" : 1,
   "b2" : 2,        
   "f1" : 0
}

Basically you do not serialize the field as a separate class, but rather pull the fields to its parent object in the tree.

I know that this could be done with a custom serializer, but I am curios if there is a simple annotation style for this. (For a single field I could have annotated with @JsonValue)

Upvotes: 4

Views: 2650

Answers (1)

varren
varren

Reputation: 14731

You can use @JsonUnwrapped

class Foo{
    @JsonUnwrapped
    public Bar bar;
    public int f1 = 1;
}

If you can't edit your class, then use Mixin or custom serializer.

Use @JsonCreator if you need deserialization

Upvotes: 6

Related Questions