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

I have a model like this:

public class Employee {
    @JsonProperty("emplyee_id")
    private Integer id;
    @JsonProperty("emplyee_first_name")
    private String firstName;
    @JsonProperty("emplyee_last_name")
    private String lastName;
    @JsonProperty("emplyee_address")
    private String address;
    @JsonProperty("emplyee_age")
    private Byte age;
    @JsonProperty("emplyee_level")
    private Byte level;

    //getters and setters
}

now I need to create two JSON using this (only) model.

the first should like, for example:

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

and the second should look like this:

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

By the way, I already tested @JsonIgnoreand @JsonInclude(JsonInclude.Include.NON_NULL).

problem of the first (as far as I know), these fields cannot be included in other JSON (for example, if you levelget this annotation, it will not be included in the second JSON)

and the second problem is that values nullcannot be included in JSON.

NULL - JSON ? , ? , - .

.

+4
1

@JsonView

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
 }

json- @JsonView (Public/Base.class), jsonview

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

:

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

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

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

Source: https://habr.com/ru/post/1681084/


All Articles