Want to hide some fields of an object that are being mapped to JSON by Jackson

后端 未结 7 1873
北海茫月
北海茫月 2020-11-30 03:45

I have a User class that I want to map to JSON using Jackson.

public class User {
    private String name;
    private int age;
    prviate int securityCode;         


        
相关标签:
7条回答
  • 2020-11-30 04:31

    Adding this here because somebody else may search this again in future, like me. This Answer is an extension to the Accepted Answer

    You have two options:
    
    1. Jackson works on setters-getters of fields. So, you can just remove getter of field which you want to omit in JSON. ( If you don't need getter at other place.)
    
    2. Or, you can use the `@JsonIgnore` [annotation of Jackson][1] on getter method of that field and you see there in no such key-value pair in resulted JSON. 
    
            @JsonIgnore
            public int getSecurityCode(){
               return securityCode;
            }
    

    Actually, newer version of Jackson added READ_ONLY and WRITE_ONLY annotation arguments for JsonProperty. So you could also do something like this.

    @JsonProperty(access = Access.WRITE_ONLY)
    private String securityCode;
    

    instead of

    @JsonIgnore
    public int getSecurityCode(){
      return securityCode;
    }
    
    0 讨论(0)
提交回复
热议问题