【问题标题】:How to ignore @JsonProperty when Serialization in JavaJava中序列化时如何忽略@JsonProperty
【发布时间】:2014-01-08 20:05:55
【问题描述】:

反序列化时的json字符串

{"rCode":"1234"} 反序列化到帐户

public class Account {
    @JsonProperty("rCode")
    private String reasonCode;
}

但是,当将 Account 序列化给其他人时 如下:

{"reasonCode":"1234"}

序列化时如何忽略@JsonProperty("rCode")? 要么 序列化时如何改变json的属性名?

【问题讨论】:

  • 你的问题不清楚。序列化将其恢复为对象形式,不是吗?你能提供更多细节吗?您为两者都显示了反序列化格式。

标签: json serialization jackson


【解决方案1】:

使用分别用@JsonGetter@JsonSetter 注释的简单访问方法,每个方法都配置了所需的json 属性名称。 在您的情况下,代码可能是这样的:

public class Account {

    private String reasonCode;

    @JsonGetter("reasonCode")
    public String getReasonCode() {
        return reasonCode;
    }

    @JsonSetter("rCode")
    public void setReasonCode(String reasonCode) {
        this.reasonCode = reasonCode;
    }
}

【讨论】:

    【解决方案2】:

    简单的方法:

    enum class MyEnum {
        @JsonProperty("1")
        ON, 
    
        @JsonProperty("0")
        OFF;
    
        @JsonValue
        fun serialize(): String {
            return this.name
        }
    }
    

    所以这个枚举会正确地将输入值 0、1 读取为 OFF、ON 但在序列化之后,对象的输出值将是 OFF、ON 仍然

    【讨论】:

      猜你喜欢
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 2015-06-23
      • 1970-01-01
      相关资源
      最近更新 更多