gpt4 book ai didi

java - JsonView 序列化取决于某些条件/属性名称等

转载 作者:行者123 更新时间:2023-12-01 17:11:34 26 4
gpt4 key购买 nike

我的一个类有 3 个相同类型的属性。现在我正在尝试将其序列化为 JSON,但其中一个属性需要以不同的方式序列化 - 基本上这些属性之一是“内部”,我只需要它的 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) 标记 createdBy 字段
  2. 按如下方式实现自定义序列化器:
    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();
}
}

关于java - JsonView 序列化取决于某些条件/属性名称等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61425693/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com