Jackson: remove some values from json and keep some null values

前端 未结 1 1348
旧时难觅i
旧时难觅i 2021-01-14 02:54

I have a model like this:

public class Employee {
    @JsonProperty(\"emplyee_id\")
    private Integer id;
    @JsonProperty(\"emplyee_first_name\")
    pr         


        
1条回答
  •  再見小時候
    2021-01-14 03:35

    it could be useful for you using @JsonView annotation

    public class Views {
        public static class Public {
        }
        public static class Base {
        }
     }
    
    
    
    public class Employee {
       @JsonProperty("emplyee_id")
       @JsonView({View.Public.class,View.Base.class})
       private Integer id;
    
       @JsonProperty("emplyee_first_name")
       @JsonView(View.Public.class)
       private String firstName;
    
       @JsonProperty("emplyee_last_name")
       @JsonView(View.Public.class)
       private String lastName;
    
       @JsonProperty("emplyee_address")
       private String address;
    
       @JsonProperty("emplyee_age")
       private Byte age;
    
       @JsonProperty("emplyee_level")
       @JsonView(View.Base.class)
       private Byte level;
    
       //getters and setters
     }
    

    in your json response add @JsonView(Public/Base.class) it will return based on jsonview annotations

    //requestmapping
    @JsonView(View.Public.class)  
    public ResponseEntity getEmployeeWithPublicView(){
        //do something
    }
    

    response:

    { 
      "employee_id":101,
      "employee_first_name":"Alex",
      "employee_last_name":"Light",
      "employee_age":null,
      "employee_address":null
    }
    

    for the second one

    //requestmapping
    @JsonView(View.Base.class)  
    public ResponseEntity getEmployeeWithBaseView(){
        //do something
    }
    

    response

    {
       "employee_id":101,
       "employee_level":5
    }
    

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