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

后端 未结 7 1872
北海茫月
北海茫月 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:11

    If you don't want to put annotations on your Pojos you can also use Genson.

    Here is how you can exclude a field with it without any annotations (you can also use annotations if you want, but you have the choice).

    Genson genson = new Genson.Builder().exclude("securityCode", User.class).create();
    // and then
    String json = genson.serialize(user);
    
    0 讨论(0)
  • 2020-11-30 04:16

    you also can gather all properties on an annotation class

    @JsonIgnoreProperties( { "applications" })
    public MyClass ...
    
    String applications;
    
    0 讨论(0)
  • 2020-11-30 04:17

    I had a similar case where I needed some property to be deserialized (JSON to Object) but not serialized (Object to JSON)

    First i went for @JsonIgnore - it did prevent serialization of unwanted property, but failed to de-serialize it too. Trying value attribute didn't help either as it requires some condition.

    Finally, working @JsonProperty with access attribute worked like a charm.

    0 讨论(0)
  • 2020-11-30 04:18

    Field Level:

    public class User {
        private String name;
        private int age;
        @JsonIgnore
        private int securityCode;
    
        // getters and setters
    }
    

    Class Level:

    @JsonIgnoreProperties(value = { "securityCode" })
    public class User {
        private String name;
        private int age;
        private int securityCode;
    }
    
    0 讨论(0)
  • 2020-11-30 04:21

    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 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;
      }
      
    0 讨论(0)
  • 2020-11-30 04:23

    if you are using GSON you have to mark the field/member declarations as @Expose and use the GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()

    Don't forget to mark your sub classes with @Expose otherwise the fields won't show.

    0 讨论(0)
提交回复
热议问题