杰克逊为什么还要将瞬态成员序列化? [英] Why jackson is serializing transient member also?
问题描述
我使用Jackson 2.1.4将POJO序列化为JSON,但我想忽略序列化的特定字段。我使用了瞬态,但它仍在序列化该元素。
I am serializing a POJO into JSON using Jackson 2.1.4 but I want to ignore a particular field from getting serialized. I used transient but still it is serializing that element.
public class TestElement {
int x;
private transient String y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public String getY() {
return y;
}
public void setY(String y) {
this.y = y;
}
}
我序列化如下:
public static void main(String[] args) throws JsonProcessingException {
TestElement testElement = new TestElement();
testElement.setX(10);
testElement.setY("adasd");
ObjectMapper om = new ObjectMapper();
String serialized = om.writeValueAsString(testElement);
System.err.println(serialized);
}
请不要建议 @JsonIgnore
因为我不想将我的模型与杰克逊特定的注释联系起来。可以仅使用瞬态完成吗? objectmapper上有可用于可见性设置的API吗?
Please don't suggest @JsonIgnore
as I don't want to tie my model to jackson specific annotations. Can it be done using transient only? Is there any API on objectmapper for visibility settings?
推荐答案
Jackson序列化瞬态的原因
member是因为getter用于确定序列化的内容,而不是成员本身 - 并且因为 y
有一个公共getter,它会被序列化。
如果你想更改默认值并让Jackson使用字段 - 只需:
The reason Jackson serializes the transient
member is because the getters are used to determine what to serialize, not the member itself - and since y
has a public getter, that gets serialized.
If you want to change that default and have Jackson use fields - simply do:
om.setVisibilityChecker(
om.getSerializationConfig().
getDefaultVisibilityChecker().
withFieldVisibility(JsonAutoDetect.Visibility.ANY).
withGetterVisibility(JsonAutoDetect.Visibility.NONE));
忽略序列化属性的另一种方法是直接在类上执行:
Another way to ignore a property on serialization is to do it directly on the class:
@JsonIgnoreProperties(value = { "y" })
public class TestElement {
...
另一种方式直接在现场:
And another way is directly on the field:
public class TestElement {
@JsonIgnore
private String y;
...
希望这会有所帮助。
这篇关于杰克逊为什么还要将瞬态成员序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!