简体   繁体   English

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)不起作用

[英]@JsonProperty(access = JsonProperty.Access.WRITE_ONLY) not working

While serialization of the class DataType the dbOptions is been ignored but dataType is being printed with its value. 在对类DataType进行序列化时,忽略了dbOptions,但正在使用其值打印dataType。

Note I need to ignore the these property only during serialization and not deserialization. 注意我只需要在序列化期间忽略这些属性而不是反序列化。

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

}

Sample output is : 示例输出是:

"options":{"dataType":"NumberRange","id":"1","min":0,"max":30}

Don't want dataType to get printed in the output 不希望在输出中打印dataType

It seems this unexpected behaviour is a bug (see https://github.com/FasterXML/jackson-databind/issues/935 ). 看来这种意外行为是一个错误(参见https://github.com/FasterXML/jackson-databind/issues/935 )。 So you have to work around the issue. 所以你必须解决这个问题。 One of the solutions is explained here http://www.davismol.net/2015/03/21/jackson-using-jsonignore-and-jsonproperty-annotations-to-exclude-a-property-only-from-json-deserialization/ . 其中一个解决方案在这里解释http://www.davismol.net/2015/03/21/jackson-using-jsonignore-and-jsonproperty-annotations-to-exclude-a-property-only-from-json-deserialization /

The following is an example from the latter link adapted to mimic the intended behaviour of the @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) annotation. 以下是后一个链接的示例,该链接适用于模仿@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;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM