根据另一个字段值对一个字段进行序列化和反序列化

时间:2018-11-18 10:58:09

标签: java android json jackson jackson-databind

如何根据同一类中的另一个字段值对字段进行序列化或反序列化?

在下面的示例中,当序列化或反序列化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字符串。

1 个答案:

答案 0 :(得分:0)

类似于@ comment,更新有效负载获取器以返回不同的输出值

 public String getPayload() {
     return "(" + getType().name().toLowerCase() + ") " +  this.payload;
 }