当前位置: 代码迷 >> java >> 在 Spring Web 应用程序中创建自定义 JSONresponse
  详细解决方案

在 Spring Web 应用程序中创建自定义 JSONresponse

热度:69   发布时间:2023-07-31 11:27:21.0

我是 Spring Boot 的新手,我不知道如何处理 JSON 响应。 希望您能够帮助我。

这是我的模型

 @Entity
public class Employee {
    private @Id @GeneratedValue Long id;
    private String name;
    private String role;

    public Employee() {}

    public Employee(String name, String role) {
        this.name = name;
        this.role = role;
}

我的仓库

public interface EmployeeRepository extends JpaRepository<Employee, Long> {}

我的控制器

@RestController
public class EmployeeController {
    private final EmployeeRepository repository;

    @GetMapping("employees/{id}")
    Employee one(@PathVariable Long id) {
        return repository.findById(id);
}

我的 JSON 文件响应

{"id":1,"name":"Bilbo Baggins","role":"burglar"},

我想要一些东西

{
 "id": 1,
 "name": "Bilbo Baggins",
 "role": "burglar",
 "_links": {
   "self": {
     "href": "http://localhost:8080/employees/1"
   },
   "employees": {
     "href": "http://localhost:8080/employees"
   }
 }
}

通过向 JSON 文件添加更多详细信息。 我使用 Hateoas 遵循了 spring.io 上的指南,但没有用。 我认为可能有另一种方法可以做到这一点。

感谢您的帮助

您需要添加 HATEOAS 依赖项。 在 Maven 中,这将是:

<dependency>
    <groupId>org.springframework.hateoas</groupId>
    <artifactId>spring-hateoas</artifactId>
    <version>0.19.0.RELEASE</version>
</dependency>
  相关解决方案