我有一个类(无法修改),例如
public class Standing {
private Integer positionNumber;
private String positionText;
private BigDecimal points;
..
}
反序列化时我得到如下数据:
{
"position": "1",
"points": 10
}
由于我无法修改 Standing
类,所以我有一个混合:
@JsonDeserialize(converter = StandingSanitizer.class)
public abstract class StandingMixIn {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
Integer positionNumber;
@JsonProperty(value = "position", access = JsonProperty.Access.WRITE_ONLY)
String positionText;
}
由于接收到的 json 没有 positionNumber
和 positionText
字段,因此我使用 @JsonPropery
注释。
使用Access.READ_ONLY
,我只是忽略positionNumber
字段。
使用 positionText
字段上的 @JsonProperty(value = "position", access = JsonProperty.Access.WRITE_ONLY)
我确保它填充有 反序列化过程中 json 中的position
字段。
这在反序列化期间效果很好。
注意 StandingSanitizer
设置 positionNumber
。这是因为接收到的 position
值可以是非数字值,例如 DSQ
,在这种情况下,positionNumber
字段将为 null
.
但是在序列化时,我想输出 Standing
类中的所有 3 个字段,例如:
{
"positionText": "1",
"positionNumber": 1,
"points": 10
}
但是由于 positionText
字段上的 @JsonProperty(value = "position", access = JsonProperty.Access.WRITE_ONLY)
,不幸的是它没有被序列化。
理论上我想做一些类似的事情:
@JsonDeserialize(converter = StandingSanitizer.class)
public abstract class StandingMixIn {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
Integer positionNumber;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@JsonProperty(value = "position", access = JsonProperty.Access.WRITE_ONLY)
String positionText;
}
我可以在读取和写入时使用不同的@JsonProperty
注释。
但是这是不可能的,因为不允许在字段上使用重复的 @JsonProperty
注释;据我所知,不支持可重复注释。
还有其他办法可以解决这个问题吗?
我能想到的一件事是拥有 2 个 ObjectMapper 实例,以及 2 个不同的 StandingMixIns; 1 用于反序列化,1 用于序列化。但我更愿意保留 1 个 ObjectMapper 实例,因此使用 2 个实例是最后的手段。
最佳答案
谢谢@Franjavi,你确实是对的,我应该在 getter/setter 上使用注释,而不仅仅是在字段上。我只专注于使用字段,因为我的混合类是用 Groovy 编写的,带有隐式 getter/setter。
我将类(class)精简为:
public abstract class StandingMixIn {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
Integer positionNumber;
@JsonProperty(value = "positionText")
public abstract String getPositionText();
@JsonProperty(value = "position")
public abstract void setPositionText(String positionText);
}
(完全删除 positionText
并使用抽象方法)
关于java - 在同一字段上读取和写入不同的 @JsonProperty 配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69398548/