我的一个班级有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,
}
}
我认为我有解决方法。
首先,我在事务类中添加了getter,如下所示:
public Company getCreatedBy() {
return new Wrapper(createdBy);
}
Wrapper类的内容是:
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class Wrapper extends Company {
private Company c;
public Wrapper(Company c) { this.c = c; }
@JsonIgnore public String getName() { return null; }
@JsonIgnore public String getAddress() { return null; }
@JsonView(View.IdOnly.class) public long getId() { return super.getId(); }
}
否,我只有createdBy
属性的ID,而其他属性的完整数据。