依赖于某些 condition/property 名称等的 JsonView 序列化

JsonView serialization that depends on some condition/property name etc

我的一个 类 有 3 个相同类型的属性。现在我正在尝试将它序列化 JSON,但是其中一个属性需要以不同的方式序列化 - 基本上其中一个属性是 "internal",我只需要它的 id,其余的必须完全序列化。

到目前为止我得到了什么:

@NoArgsConstructor @AllArgsConstructor @Data
public static class Id {
    @JsonView(View.IdOnly.class) private long id;
}

@NoArgsConstructor @AllArgsConstructor @Data
public static class Company extends Id {
    @JsonView(View.Tx.class) private String name;
    @JsonView(View.Tx.class) private String address;
}

@NoArgsConstructor @AllArgsConstructor @Data
public static class Transaction {
    @JsonView(View.Tx.class)     private Company from;
    @JsonView(View.Tx.class)     private Company to;
    @JsonView(View.IdOnly.class) private Company createdBy;
}

public static class View {
    public interface Tx extends IdOnly {}
    public interface IdOnly {}
}

并对其进行快速测试:

@Test
void test() throws JsonProcessingException {
    Company s = new Company("Source", "address_from");
    Company d = new Company("Destination", "address_to");
    final Transaction t = new Transaction(s, d, s);

    final ObjectMapper m = new ObjectMapper();
    System.out.println(m.writerWithDefaultPrettyPrinter().withView(View.Tx.class).writeValueAsString(t));
}

输出为:

{
  "from" : {
    "id" : 0,
    "name" : "Source",
    "address" : "address_from"
  },
  "to" : {
    "id" : 0,
    "name" : "Destination",
    "address" : "address_to"
  },
  "createdBy" : {
    "id" : 0,
    "name" : "Source",
    "address" : "address_from"
  }
}

现在,问题是,如何自定义 createBy 属性 的序列化?我需要以下输出:

{
  "from" : {
    "id" : 0,
    "name" : "Source",
    "address" : "address_from"
  },
  "to" : {
    "id" : 0,
    "name" : "Destination",
    "address" : "address_to"
  },
  "createdBy" : {
    "id" : 0,
  }
}

哦,我认为答案很简单:

  1. @JsonSerialize(using = CS.class)
  2. 标记 createdBy 字段
  3. 按如下方式实现自定义序列化程序:
    public static class CS extends JsonSerializer<Company> {
        @Override
        public void serialize(Company company, JsonGenerator jgen, SerializerProvider serializerProvider) throws IOException {
            jgen.writeStartObject();
            jgen.writeNumberField("id", company.getId());
            jgen.writeEndObject();
        }
    }