gpt4 book ai didi

java - Spring Boot - 分层实体数据未从 REST API 返回

转载 作者:行者123 更新时间:2023-12-02 10:29:36 25 4
gpt4 key购买 nike

我在 Spring Boot 中为类(class)实现了一个 API 方法。它按主题 ID 获取类(class)。 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 获取所有类(class)并将其作为 RestMessage 对象返回。我使用 postman 进行测试,在响应中我得到了类(class)列表,但主题实体数据被丢弃。

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 响应后,所有类(class)的 Topic 对象都会被截断。

附上调试数据图像:

enter image description here

我想知道在这种情况下我做错了什么?

最佳答案

Course 中的字段 topic 没有 getter,这就是 JSON 序列化程序忽略的原因。

关于java - Spring Boot - 分层实体数据未从 REST API 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53685396/

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