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 the class A

the JSON construction using the codehaus.jackson

API.

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

.

+3


source to share


1 answer


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 shown below. (Make sure your defName field getter name is as getDefName () in your B class, or change it in Mixin class to be yours.)

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



Prints:

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

      

+1


source







All Articles