Jackson:将同一个对象序列化为多个JSON

dgenwo3n  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(160)

我有两个POJO,看起来像:

public ResponseA {
  private HeavyObject object;
  private AdditionalDataA additionalData;

  public ResponseA(HeavyObject object, AdditionalDataA additionalData) {
    this.object = object;
    this.additionalData = additionalData;
  }
}

个字符
然后我有一个方法,将这些对象发送到不同的端点,类似于:

public void sendResponses(
      ObjectMapper mapper, 
      HeavyObject object, 
      AdditionalDataA addDataA, 
      AdditionalDataB addDataB) {

    // Here object is serialized twice, which is costly!
    String jsonA = mapper.writeValueAsString(new ResponseA(object, addDataA));
    String jsonB = mapper.writeValueAsString(new ResponseB(object, addDataB));
    sendResponseA(jsonA);
    sendResponseB(jsonB);
}


有没有一种方法可以序列化这些响应,使HeavyObject只序列化一次?

von4xj4u

von4xj4u1#

是的,您可以使用@JsonRawValue注解ResponseAResponseB中的object字段,将其转换为String,并在单独的步骤中序列化它。

相关问题