@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)不起作用
问题描述:
在类DataType的序列化过程中,dbOptions被忽略,但dataType正在打印其值。@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)不起作用
注意我只需在序列化期间忽略这些属性而不是反序列化。
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "dataType")
@JsonSubTypes(value = {
@JsonSubTypes.Type(value = DefaultType.class, name = "Default"),
@JsonSubTypes.Type(value = NumberRangeType.class, name = "NumberRange"),
})
public abstract class DataType {
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
protected String dataType;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
protected String dbOptions;
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getDbOptions() {
return dbOptions;
}
public void setDbOptions(String dbOptions) {
this.dbOptions = dbOptions;
}
abstract
public void compute() throws ParseException;
}
示例输出:
"options":{"dataType":"NumberRange","id":"1","min":0,"max":30}
不想数据类型来获得打印输出
答
看来这意外的行为是一个bug(见https://github.com/FasterXML/jackson-databind/issues/935)。所以你必须解决这个问题。其中一个解决方案在这里解释http://www.davismol.net/2015/03/21/jackson-using-jsonignore-and-jsonproperty-annotations-to-exclude-a-property-only-from-json-deserialization/。
以下是适用于模仿@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)注释的预期行为的后一个链接的示例。
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
public class User implements Serializable {
@JsonIgnore
private String password;
@JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty
public void setPassword(String password) {
this.password = password;
}
}