杰克逊:从 JSON 中删除一些值并保留一些空值。

4
我有一个像这样的模型:
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
}

现在我需要使用这个(唯一的)模型创建两个JSON。
第一个JSON应该像这样,例如:
{
    "employee_id":101,
    "employee_first_name":"Alex",
    "employee_last_name":"Light",
    "employee_age":null,
    "employee_address":null
}

第二个示例必须像这样,例如:

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

顺便说一下,我已经测试过@JsonIgnore@JsonInclude(JsonInclude.Include.NON_NULL)。第一个的问题(据我所知)是这些字段不能包含在其他JSON中(例如如果level获取此注释,则不会包含在第二个JSON中)。第二个的问题是,null值不能包含在JSON中。那么我能保留null值并防止某些其他属性被包含在JSON中,而无需创建额外的模型吗?如果答案是肯定的,那么该怎么做呢?如果不是,我真的很感谢任何人给我最好的解决方案。非常感谢。

1
请使用 @JsonView(XXX.class) 注解。 - Kalaiselvan
@KalaiselvanA 我能否使用此注释在两个JSON中使用同一字段? - Seyed Ali Roshan
1个回答

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
}

我很确定它会起作用,但让我先检查一下。谢谢你的回答。 - Seyed Ali Roshan
非常感谢您的解决方案。它完美地解决了我的问题。我只是使用接口来代替类作为视图。 - Seyed Ali Roshan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接