Ashok kumar
Ashok kumar

Reputation: 195

How to ignore json property in encapsulated design

class A{ 
   private B b; 
   //other properties
   //getter setter
}
// unable to add jsonIgnore in this class due to dependency in other module
class B {
   int id;
   String name;
   String defname;
}

I want to ignore defname in class A JSON building by codehaus.jackson API.

I need {a:{id:value,name:value}}.

Upvotes: 3

Views: 588

Answers (1)

Sercan Ozdemir
Sercan Ozdemir

Reputation: 4691

You can use Mixin for this purpose.

  • First Create an abstract class with JsonIgnore annotation:

    abstract class MixIn{
         @JsonIgnore
         abstract String getDefname(); }
    
  • Then use it as below. (Be sure your getter name of defName field as getDefName() in your B class or change it in Mixin class as yours.)

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixIn( B.class, MixIn.class );
    objectMapper.writeValue( System.out, new A() );
    

This prints:

{"b":{"id":1,"name":"Sercan"}}

Upvotes: 1

Related Questions