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

I am serializing as following:

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);
}

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序列化transient个成员的原因是,getter用于确定要序列化的内容,而不是成员本身——而且由于y有一个公共getter,所以会被序列化.

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

Hope this helps.

Json相关问答推荐

如何使用表键名称GROUP_BY

我可以使用JQ来缩小数组中的json对象的范围吗?

Python将Pandas转换为嵌套的JSON

JQ如何获取特定子元素的所有父母

如何在Haskell中解析JSON,其中字段的名称可以是多个值之一,但应该转换为单个Haskell类型?

来自json的可分析的构建报告

在Ruby的json中压缩单个字段

震动范围改善

如何强制仅有一个元素的数组在JSON中生成方括号

使用 jolt 将对象数组转换为数组

颠簸转换问题

如何从 json 中获取单个元素?

修改 boost::json::object 中的值

JOLT 在 struct 体中间添加一个 JSON 字段

JSON 字段的多个名称

SwiftUI:如何使用 0 索引数组键为 JSON 添加类型

使用 jq 将键值行转换为 json

如何在 Node.js 中解析包含NaN的 JSON 字符串

使用 jq 从 bash 中管道分隔的键和值创建 JSON

在 Django 1.9 中,使用 JSONField(本机 postgres jsonb)的约定是什么?