Search code examples
javajax-rsjackson2

How can I NOT serialize some part (subobject) of an Object using JAX-RS interface?


I have the following classes:

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
}

I "own" class A in my project, by classes B and C comes from another project (JAR dependency included in DOM). I collect information of B by calling a REST interface. Along with B, comes C, which contains a password in it.

When I send A to the user, all objects are serialized. This way, C (and the password) goes along.

How can I send A with B, but omit C?

I can't change B and C:

  1. I can't put @JsonIgnore on C in class B;
  2. There is not setter in B, so i can't a.getB().setC(null).

Here comes the real question: 1. Is there any annotation I can put in my REST interface (I use RESTEasy) so that Jackson can serialize without the C class?

  1. Or, if not, how could I do that by coding?

I would not like to create another object "B-like" and copy all the properties. There should be a better way (I hope).


Solution

  • You can use @JsonIgnoreProperties annotation from com.fasterxml.jackson.annotation on "b":

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

    I hope it helps you.