java - @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 不工作

标签 java serialization jackson mongo-jackson-mapper

虽然类 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}

不想在输出中打印数据类型

最佳答案

似乎这种意外行为是一个错误(参见 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;
  }
}

关于java - @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37697359/

相关文章:

java - PriorityQueue添加元素会改变元素,奇怪的bug

python - 如何在 Django 中使用多个嵌套字段覆盖序列化程序中的创建方法?

java - Spring RestTemplate - 指定 Jackson View

java - 在 spring-boot 中为 Graphite 千分尺事件添加前缀

java - 如何为相似的行添加 Arraylist 项

java - 缺少 jar 会影响 Fortify 扫描结果吗?

c# - 如何让 BinaryFormatter 在不同的应用程序中反序列化

.net - 序列化同一个对象会产生不同的流吗?

java - Jackson 反序列化内部集合

java - Jackson Databind - 获取 pojo 中未指定的属性