3 回答
TA贡献1801条经验 获得超8个赞
Spring boot 使用 Jackson 进行 JSON 序列化和反序列化,尝试使用 @JSONIgnore (com.fasterxml.jackson.annotation.JsonIgnore)。
TA贡献1818条经验 获得超7个赞
为您的要求
PatientDTO.java
public class PatientDTO {
private Check check;
@JsonIgnoreProperties(value = {"id", "dob", "username", "password"})
private Object details;
/* Getter & Setter */
public enum Check {
SUCCESS("Success"),
FAILURE("Failure");
private String name;
Check(String name) {
this.name = name;
}
@JsonValue
public String getName() {
return name;
}
}
}
控制器演示:
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/patient")
public PatientDTO getPatient() {
PatientDTO patientDTO = new PatientDTO();
patientDTO.setCheck(PatientDTO.Check.SUCCESS);
patientDTO.setDetails(new Patient());
return patientDTO;
}
}
更好的方法
使用 http 状态
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Patient {
private long id;
private String name;
private Date dob;
private String phoneNo;
private String email;
private Address address;
private String username;
private String password;
/* Getter & Setter */
}
控制器演示:
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("patient")
// or @ResponseStatus(HttpStatus.OK)
public ResponseEntity<Patient> patient() {
Patient patient = new Patient();
patient.setId(123);
patient.setName("123");
patient.setEmail("demo@demo.com");
patient.setPassword(null); // set to null to ignore password
return ResponseEntity.ok(patient);
}
}
TA贡献1828条经验 获得超4个赞
只需创建另一个对象并将其用作您的 restful 控制器的响应;
public class PatientResponse implements Serializable {
private static final long serialVersionUID = 2L;
private Check check;
private Detail details;
// getter, setter, etc
public static class Detail {
private String name;
private String phoneNo;
private String email;
private String address;
// getters, setters, etc
}
public enum Check {
Success, Failure
}
}
& 在控制器中
@RestController
public class PatientController {
@GetMapping(...)
public PatientResponse get(...) {
Patient patient = ... // get patient somehow
return mapPatientToResponse(patient); // map Patient to PatientResponse here
}
}
添加回答
举报