【问题标题】:Jackson: remove some values from json and keep some null values杰克逊:从 json 中删除一些值并保留一些空值
【发布时间】:2017-12-13 17:36:23
【问题描述】:

我有一个这样的模型:

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。

第一个必须像这样,例如:

{
    "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 中。

那么我是否可以保留空值并防止某些其他属性包含在 JSON 中而不创建额外的模型?如果答案是肯定的,那我该怎么做?如果不是,我真的很感激有人给我这个状态的最佳解决方案。

非常感谢。

【问题讨论】:

  • 使用@JsonView(XXX.class)注解
  • @KalaiselvanA 我可以在两个 JSON 中使用带有此注释的字段吗?

标签: java json jackson


【解决方案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
}

【讨论】:

  • 我很确定它会起作用,但让我先检查一下。谢谢你的回答
  • 我真的非常感谢您的解决方案。它非常适合我的情况。我只是使用 Views 的接口而不是类
猜你喜欢
  • 2017-05-05
  • 1970-01-01
  • 2022-12-24
  • 1970-01-01
  • 2018-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
相关资源
最近更新 更多