Jackson 自定义序列化以展平对象

Ric*_*ard 2 java serialization json jackson deserialization

我有一个像这样的java pojo:

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
}
Run Code Online (Sandbox Code Playgroud)

我想将FooA对象序列化为这个 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
}
Run Code Online (Sandbox Code Playgroud)

注意 FooA 是如何扁平化的。而不是:

"fooB":{  
      "t":"fooBString",
      "i1":100,
      "i2":200
}
Run Code Online (Sandbox Code Playgroud)

在 JSON 的底部,它被扁平化以将这些字段提取到父 json 中。

我可以像这样编写自定义序列化程序:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,您拥有的字段越多,这会变得非常麻烦FooA

那么有没有办法告诉杰克逊只序列化FooA通常情况下的所有字段,除了FooB fooB在父json中提取字段时,它应该在哪里进行自定义序列化。

我基本上不想要任何嵌套的 JSON。

Sac*_*141 8

您不需要为此用例编写自定义序列化程序。只需@JsonUnwrappedFooB.

例如:

class FooA {
    private String s1;
    private String s2;

  // other fields 

    @JsonUnwrapped
    private FooB fooB;

//getter setter

}
Run Code Online (Sandbox Code Playgroud)