8

在对 DataType 类进行序列化时,忽略 dbOptions,但正在打印 dataType 及其值。

注意我只需要在序列化而不是反序列化期间忽略这些属性。

@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}

不希望 dataType 在输出中打印

4

1 回答 1

9

似乎这种意外行为是一个错误(请参阅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;
  }
}
于 2016-06-14T23:22:01.430 回答