Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 800
Radu Ionescu Avatar asked Oct 26 '25 22:10

Radu Ionescu


1 Answers

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

like image 171
varren Avatar answered Oct 30 '25 02:10

varren