我在 Spring Boot 中为课程实现了一个 API 方法。它按主题 ID 获取课程。 Course 类的实现为:
@Entity
public class Course {
@Id
private String id;
private String name;
private String description;
@ManyToOne
private Topic topic;
public Course() {
}
public Course(String id, String name, String description, String topicId) {
super();
this.id = id;
this.name = name;
this.description = description;
this.topic = new Topic(topicId, "", "");
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setTopic(Topic t) {
this.topic = t;
}
}
API方法实现为:
@RequestMapping(method=RequestMethod.GET, value="/topics/{topicId}/courses")
public RestMessage getAllCourses(@PathVariable String topicId) {
try {
List<Course> course = courseService.getAllCourses(topicId);
message = new RestMessage(course,StatusCodeEnum.OK);
return message;
} catch (Exception e) {
message = new RestMessage(e.getMessage(),StatusCodeEnum.INTERNAL_SERVER_ERROR);
message.setException(e);
return message;
}
}
方法实现很简单,它尝试根据主题id获取所有课程并将其作为RestMessage对象返回。我正在使用邮递员进行测试,在响应中我得到了课程列表,但主题实体数据被丢弃。
API响应如下:
{
"data": [
{
"id": "java-streams",
"name": "Java Streams",
"description": "Java Stream learning"
}
],
"httpStatus": "OK",
"statusCode": 200,
"exception": null
}
RestMessage 类定义为:
public class RestMessage {
private Object data;
private StatusCodeEnum httpStatus;
private int statusCode;
private Exception ex;
public RestMessage() {
}
public RestMessage(Object d, StatusCodeEnum c) {
data = d;
httpStatus = c;
statusCode = c.val();
}
public void setData(Object d) {
data =d;
}
public void setHttpStatus(StatusCodeEnum c) {
httpStatus = c;
}
public void setStatusCode(int c) {
statusCode = c;
}
public void setException(Exception e) {
ex = e;
}
public void setStatusCode(StatusCodeEnum c) {
httpStatus = c;
}
public Object getData() {
return data;
}
public StatusCodeEnum getHttpStatus() {
return httpStatus;
}
public Exception getException() {
return ex;
}
public int getStatusCode() {
return statusCode;
}
}
但是,我尝试调试 API 端点,在返回 RestMessage 对象之前,我有所需形状的数据,但在获取 json 响应后,所有课程的 Topic 对象都被截断。
附调试数据图:
我想知道在这种情况下我做错了什么?
来自
topic
的字段 Course
没有 getter,这就是 JSON 序列化器忽略的原因。
您可以使用Lombok注释自动生成getter和setter。
只需在类定义上添加
@Data
,您将生成 getter 和 setter,以及不带参数的构造函数。您将拥有您所说的POJO类的一切。
检查此链接:龙目岛项目
@Data
@Entity
public class Course implements Serializable