如何根据同一类中的另一个字段值对字段进行序列化或反序列化?
在下面的示例中,当序列化或反序列化Packet
类时,我希望type
字段将确定如何 payload
字段将被序列化和反序列化
PayloadType枚举
public enum PayloadType {
HTTP,
HTTPS,
FTP
}
数据包类
public class Packet {
private final String payload;
// This field should determine how "payload" field is serialized.
private final PayloadType type;
private final Date creationTime;
@JsonCreator
public Packet(String payload, PayloadType type) {
this.payload = payload;
this.type = type;
this.creationTime = new Date();
}
public String getPayload() {
return this.payload;
}
public PayloadType getType() {
return this.type;
}
public Date getCreationTime() {
return this.creationTime;
}
测试
public class PacketTests {
@Test
public void packetSerialization_fromHttpType() throws JsonProcessingException {
// Given
ObjectMapper jackson = new ObjectMapper();
String payload = "hello world";
PayloadType type = PayloadType.HTTP;
Packet packet = new Packet(payload, type);
String json;
// When
json = jackson.writeValueAsString(packet);
// Then
System.out.println(json);
}
当前输出
{"payload":"hello world","type":"HTTP","creationTime":1542538836041}
预期产量
{"payload":"(http) hello world","type":"HTTP","creationTime":1542538836041}
{"payload":"(https) hello world","type":"HTTPS","creationTime":1542538836041}
{"payload":"X9hnahj83","type":"FTP","creationTime":1542538836041}
payload
中的FTP
是base64字符串。
答案 0 :(得分:0)
类似于@ comment,更新有效负载获取器以返回不同的输出值
public String getPayload() {
return "(" + getType().name().toLowerCase() + ") " + this.payload;
}