gpt4 book ai didi

java - 如何自定义 Spring Rest Controller 的 json 输出

转载 作者:行者123 更新时间:2023-12-02 03:46:48 24 4
gpt4 key购买 nike

我有一个 POJO 类患者,具有以下属性:

public class Patient implements Serializable{

private static final long serialVersionUID = 2L;

private long id;
private String name;
private Date dob;
private String phoneNo;
private String email;
private Address address;
private String username;
private String password;

....

现在,从我的休息 Controller 中,我只需要发送 json 中患者的姓名、电话号码、电子邮件和地址。我期望 json 输出为

{
"check":"Success",
"details":{
"name":"Test User",
"phoneNo":"9876544321",
"email":"test@gmail.com",
"address":"Address"
}
}

此处检查成功/失败仅作为标志添加。

最佳答案

只需创建另一个对象并将其用作您的 Restful Controller 的响应;

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
}
}

&在 Controller 中

@RestController
public class PatientController {

@GetMapping(...)
public PatientResponse get(...) {
Patient patient = ... // get patient somehow
return mapPatientToResponse(patient); // map Patient to PatientResponse here
}
}

关于java - 如何自定义 Spring Rest Controller 的 json 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56799915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com