我在做一个spring boot项目。我想从请求对象中删除空属性。这是因为在下一步中,我需要将请求对象传递给第三方api,而不使用null属性。我在网上搜索了一下,发现我可以使用jsoninclude.include.non\u null。但是对象仍然有空值。下面是我的示例代码,
模型,
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RequestTest {
private String firstname;
private String lastname;
private Integer age;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
控制器,
@PostMapping("/test/person")
public String testPerson(@RequestBody RequestTest req){
log.info(gson.toJson(req)); //I need to pass this to 3rd party API without null fields.
return "success";
}
这是我从日志里得到的,
{
"firstname": "foo",
"lastname": null,
"age": 15
}
对象仍包含空值。请帮忙。
编辑
这是我需要将对象传递给第三方api的示例代码,
public String passToThirdParty(RequestTest req){
RestTemplate restTemplate = new RestTemplate();
String url = "/xxx";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<RequestTest> entity = new HttpEntity<>( req, headers);
log.info(gson.toJson(entity)); //Inside body, it still has "lastname": null.
ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
return result.getBody();
}
在实体的日志主体中,仍然有“lastname”:null请帮助。还是需要逐个字段手动删除?
暂无答案!
目前还没有任何答案,快来回答吧!