Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson Custom Serialization to Flatten Object

I have a java pojo like so:

public class FooA {
    private String s1;
    private String s2;
    private int i;
    private double d1;
    private double d2;
    private Timestamp timestamp;
    private LocalDate date;
    private List<String> listOfStrings;
    private FooB fooB;

    //Constructors & getters
}

public class FooB {
    private String t;
    private int i1;
    private int i2;

    //Constructors & getters
}

I want to serialize the FooA object into this json:

{
   "s1":"something",
   "s2":"somethingelse",
   "i":2,
   "d1":10.0,
   "d2":20.0,
   "timestamp":38743488,
   "date":null,
   "listOfStrings":[
        "string1",
        "string2",
        "string3"
   ],
   "t":"fooBString",
   "i1":100,
   "i2":200
}

Notice how FooA is flattened. Instead of having:

"fooB":{  
      "t":"fooBString",
      "i1":100,
      "i2":200
}

At the bottom of the JSON, it's been flattened to extract those fields into the parent json.

I could write a custom serializer like so:

public class FooASerializer extends StdSerializer<FooA> {
    public FooASerializer() {
        this(null);
    }

    protected FooASerializer(final Class<FooA> t) {
        super(t);
    }

    @Override
    public void serialize(final FooA value,
                          final JsonGenerator gen,
                          final SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        gen.writeStringField("s1", value.getS1());
        gen.writeStringField("s2", value.getS2());
        gen.writeStringField("i", value.getI());
        gen.writeStringField("d1", value.getD1());
        gen.writeStringField("d2", value.getD2());
        //etc etc
        gen.writeStringField("t", value.getFooB.getT());
        gen.writeStringField("i1", value.getFooB.getI1());
        gen.writeStringField("i2", value.getFooB.getI2());
        gen.writeEndObject();
    }
}

But this can get quite cumbersome the more fields you have on FooA.

So is there a way to tell Jackson to just serialize all the fields in FooA normally EXCEPT for FooB fooB where it should do a custom serialization insofar as extracting the fields in the parent json.

I essentially do not want any nested JSON.

like image 901
Richard Avatar asked May 23 '26 10:05

Richard


1 Answers

You don't need to write custom serializer for this use-case. Just use @JsonUnwrapped annotation for FooB.

E.g.:

class FooA {
    private String s1;
    private String s2;

  // other fields 

    @JsonUnwrapped
    private FooB fooB;

//getter setter

}
like image 55
Sachin Gupta Avatar answered May 25 '26 00:05

Sachin Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!