我需要序列化没有给定字段的 bean,但使用该字段反序列化该 bean。我用@JsonIgnore
在 setter/getter 上,和 @JsonIgnore(false)
在 setter 上:
public class TestJson {
private String s1, s2;
@JsonIgnore
public String getS1() {
return s1;
}
@JsonIgnore(false)
public void setS1(String s1) {
this.s1 = s1;
}
public String getS2() {
return s2;
}
public void setS2(String s2) {
this.s2 = s2;
}
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
TestJson bean = new TestJson();
bean.setS1("test1");
bean.setS2("test2");
System.out.println(mapper.writeValueAsString(bean));
String json = "{\"s1\":\"test1\",\"s2\":\"test2\"}";
bean = mapper.readValue(json, TestJson.class);
System.out.println("s1=" + bean.getS1());
System.out.println("s2=" + bean.getS2());
}
}
序列化效果良好,得到预期值{"s2":"test2"}
.
但是@JsonIgnore(false)
在 setter 上似乎不起作用。
我期望:
s1=test1
s2=test2
但是得到了:
s1=null
s2=test2
如何在球场上制作二传手 s1
工作?
最佳答案
您可以将@JsonProperty
与JsonProperty.Access.WRITE_ONLY
一起使用
Access setting that means that the property may only be written (set) for deserialization, but will not be read (get) on serialization, that is, the value of the property is not included in serialization.
public class TestJson {
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String s1;
private String s2;
public String getS1() {
return s1;
}
public void setS1(String s1) {
this.s1 = s1;
}
public String getS2() {
return s2;
}
public void setS2(String s2) {
this.s2 = s2;
}
}
这也应该有效
public class TestJson {
private String s1;
private String s2;
@JsonIgnore
public String getS1() {
return s1;
}
@JsonProperty
public void setS1(String s1) {
this.s1 = s1;
}
public String getS2() {
return s2;
}
public void setS2(String s2) {
this.s2 = s2;
}
}
关于java - Jackson:我怎样才能忽略 getter 而解析 setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62896884/