[英]How do I make fields in DTO optional using lombok?
所以我有一個像這樣的 DTO,
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder
@ToString
@JsonIgnoreProperties(ignoreUnknown=true)
public class PersonDTO {
private String name;
private String address;
private String phone;
private String other;
}
我將以下有效負載傳遞給外部 API
{
"name": "John",
"phone": "123",
"address": "abc"
}
這向我拋出了 500 個內部錯誤:
HttpClientErrorException$NotFound: 404: "{<EOL> "status": "Error", <EOL> "message": "Error validating JSON. Error: - Invalid type Null, expected String."}"
如果我在 DTO 中注釋掉other
屬性,那么我將成功獲得 200 響應。 我認為@JsonIgnoreProperties
注釋應該忽略不存在的屬性,但似乎不起作用。
您正在使用 lombok 的@NoArgsConstructor
和@AllArgsConstructor
。 所以你必須使用其中一個。 如果您不想要一個全參數構造函數,則必須實現自己的。
@NoArgsConstructor
@Getter
@Setter
@Builder
@ToString
@JsonIgnoreProperties(ignoreUnknown=true)
public class PersonDTO {
private String name;
private String address;
private String phone;
private String other;
public PersonDTO(String name, String address, String phone) {
super(name, address, phone, "");
}
public PersonDTO(String name, String address, String phone, String other) {
this.name = name;
this.address = address;
this.phone = phone;
this.other = other
}
}
或者,如果您可以控制並且這是一個 Spring Boot 應用程序,您可以嘗試在控制器中使用required=false
,這樣您就可以繼續使用全 arg 構造函數。
public PersonDTO getPerson(
@PathVariable(value = "name") String name,
@PathVariable(value = "address") String address
@PathVariable(value = "phone") String phone
@PathVariable(value = "other", required = false) String other) {
....
}
該錯誤表明他們無法將Null
解析為String
。 這是一個非常有趣的錯誤,首先愚弄了我。 您的帶有其他字段null
的 json 對象可能如下所示:
{
"name": "John",
"phone": "123",
"address": "abc"
}
所以不知何故,這個 API 不能只用引號括住null
並告訴你它無法解析它。
因此,我想您需要將other
的值設置為空字符串:
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder
@ToString
@JsonIgnoreProperties(ignoreUnknown=true)
public class PersonDTO {
private String name;
private String address;
private String phone;
private String other = ""; //empty because external api can't handle null
}
如果屬性可以為空,那么您可以使用@JsonInclude(Include.NON_NULL)
。 這將允許在屬性中設置空值。 我猜,默認情況下它不允許空值。
正如您在評論中所說,添加@JsonInclude(JsonInclude.Include.NON_NULL)
是解決方案。 此注釋告訴序列化程序忽略為空的字段。 如果您不添加此內容,則有效負載將如下所示:
{
"name": "John",
"phone": "123",
"address": "abc",
"other": null
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.