使类的字段对于JSON转换是可选的

问题描述

我有一个spring-boot应用程序。我已经公开了使用JSON主体的API。 有效负载如下:

{ userName: Karan,userId: 123,age: 29,addtionalInfo: {accountType: A}

} 

我的方法一个相应的类来处理此有效负载

class PayloadDto {
private String userName;
private String userId;
private int age;
private Map<String,String> addtionalInfo;

public PayloadDto(){}

//getters
//setters
}

这很好。

最近,我们必须对我们的api进行增强。现在,我必须增强类以接受两种类型的有效负载。上面提到的一个应该可以正常工作,增强类也可以在以下新的有效负载下正常工作:

{ userName: Karan,addtionalInfo: {accountType: A}
occupationDetails : { designation: developer,email: [email protected],companyName: Alfa}

} 

您能帮我的班级看起来什么样,以便它对于这两个json负载都适用吗?

我想到这样写课:

class PayloadDto {
private String userName;
private String userId;
private int age;
private Map<String,String> addtionalInfo;
private Map<String,String> occupationDetails;
public PayloadDto(){}

//getters
//setters
}

但是这仅对第二个json有效,而对于第一个json有效负载失败。

解决方法

我将假设您的JSON实际上是有效的,并且看起来像这样:

{
  "userName": "Karan","userId": 123,"age": 29,"addtionalInfo": {
    "accountType": "A"
  },"occupationDetails": {
    "designation": "developer","email": "[email protected]","companyName": "Alfa"
  }
}

那么您的课程将是:

@JsonInclude(Include.NON_EMPTY)
class PayloadDto {
  private String userName;
  private String userId;
  private int age;

  // new data types
  private AdditionalInfo additionalInfo;
  private OccupationDetails occupationDetails;

  public PayloadDto(){}

  //getters
  //setters
}

因此,基本上,您就像创建“基”类一样,只需创建新类并定义它们的相应成员。

@JsonInclude(Include.NON_EMPTY)告诉Jackson忽略不存在的属性(您的“可选”属性)。