【问题标题】:How can I NOT serialize some part (subobject) of an Object using JAX-RS interface?如何不使用 JAX-RS 接口序列化对象的某些部分(子对象)?
【发布时间】:2018-07-31 23:58:50
【问题描述】:

我有以下课程:

class A {
    @JsonProperty("id")
    Integer id;

    @JsonProperty("b")
    B b;
    // constructors, getters, etc.
}

class B {
    @JsonProperty("id")
    Integer id

    // other properties ...

    @JsonProperty("c")
    C c;

    // getters and setters
}

class C {
    @JsonProperty("id")
    Integer id

    // other properties ...

    @JsonProperty("password")
    String password;
    // getters and setters
}

我在我的项目中“拥有”类 A,类 B 和 C 来自另一个项目(DOM 中包含 JAR 依赖项)。我通过调用 REST 接口来收集 B 的信息。与 B 一起出现的是 C,其中包含密码。

当我向用户发送 A 时,所有对象都被序列化。这样,C(和密码)就会继续。

如何发送 A 和 B,但省略 C?

我不能改变 B 和 C:

  1. 我不能将 @JsonIgnore 放在 B 类的 C 上;
  2. B 中没有 setter,所以我不能 a.getB().setC(null)。

真正的问题来了: 1. 有没有我可以在我的 REST 接口(我使用 RESTEasy)中添加注解,以便 Jackson 可以在没有 C 类的情况下进行序列化?

  1. 或者,如果没有,我如何通过编码来做到这一点?

我不想创建另一个“B-like”对象并复制所有属性。应该有更好的方法(我希望)。

【问题讨论】:

  • 我建议使用您要发送的信息构建您自己的对象并序列化该对象。

标签: java jax-rs jackson2


【解决方案1】:

您可以在“b”上使用来自 com.fasterxml.jackson.annotation 的 @JsonIgnoreProperties 注释:

class A {
    @JsonProperty("id")
    Integer id;

    @JsonProperty("b")
    @JsonIgnoreProperties({"c"})
    B b;
    // constructors, getters, etc.
}

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-18
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多