【问题标题】:Create custom JSONresponse in spring web app在 Spring Web 应用程序中创建自定义 JSONresponse
【发布时间】:2019-02-13 18:22:58
【问题描述】:

我是 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 上的指南,但它没有用。我认为可能还有另一种方法可以做到这一点。

感谢您的帮助

【问题讨论】:

    标签: java json spring spring-boot spring-data


    【解决方案1】:

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

    <dependency>
        <groupId>org.springframework.hateoas</groupId>
        <artifactId>spring-hateoas</artifactId>
        <version>0.19.0.RELEASE</version>
    </dependency>
    

    【讨论】:

    • 我添加了它,但 linkTo 和 methodOn 不像指南那样工作。 linkTo(methodOn(EmployeeController.class).one(employee.getId())).withSelfRel(),您可以在此处查看完整指南spring.io/guides/tutorials/rest
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    相关资源
    最近更新 更多