Spring Boot Consuming and Producing JSON – Spring Boot消耗和产生JSON

最后修改: 2019年 3月 21日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll demonstrate how to build a REST service to consume and produce JSON content with Spring Boot.

在本教程中,我们将演示如何构建REST服务,以便使用Spring Boot消费和生产JSON内容

We’ll also take a look at how we can easily employ RESTful HTTP semantics.

我们还将看一下我们如何能够轻松地采用RESTful HTTP语义。

For simplicity, we won’t include a persistence layer, but Spring Data also makes this easy to add.

为了简单起见,我们不会包括持久层,但是Spring Data也可以轻松地添加。

2. REST Service

2.REST服务

Writing a JSON REST service in Spring Boot is simple, as that’s its default opinion when Jackson is on the classpath:

在Spring Boot中编写JSON REST服务很简单,因为当Jackson位于classpath上时,这是它的默认意见。

@RestController
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService service;

    @GetMapping("/{id}")
    public Student read(@PathVariable String id) {
        return service.find(id);
    }

...

By annotating our StudentController with @RestController, we’ve told Spring Boot to write the return type of the read method to the response body. Since we also have a @RequestMapping at the class level, it would be the same for any more public methods that we add.

通过用@RestController注释我们的StudentController我们已经告诉Spring Boot将read方法的返回类型写入响应体中。由于我们在类的层面上也有一个@RequestMapping,所以对于我们添加的更多公共方法也是如此。

Though simple, this approach lacks HTTP semantics. For example, what would happen if we don’t find the requested student? Instead of returning a 200 or 500 status code, we might want to return a 404.

虽然简单,这种方法缺乏HTTP语义。例如,如果我们没有找到请求的学生,会发生什么?我们可能不想返回200或500状态代码,而想返回404。

Let’s take a look at how to wrest more control over the HTTP response itself, and in turn add some typical RESTful behaviors to our controller.

让我们来看看如何对HTTP响应本身进行更多的控制,并反过来给我们的控制器添加一些典型的RESTful行为。

3. Create

3.创造

When we need to control aspects of the response other than the body, like the status code, we can instead return a ResponseEntity:

当我们需要控制响应的其他方面时,比如状态代码,我们可以返回一个ResponseEntity

@PostMapping("/")
public ResponseEntity<Student> create(@RequestBody Student student) 
    throws URISyntaxException {
    Student createdStudent = service.create(student);
    if (createdStudent == null) {
        return ResponseEntity.notFound().build();
    } else {
        URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
          .path("/{id}")
          .buildAndExpand(createdStudent.getId())
          .toUri();

        return ResponseEntity.created(uri)
          .body(createdStudent);
    }
}

Here we’re doing much more than just returning the created Student in the response. We’re also responding with a semantically clear HTTP status, and if creation succeeds, a URI to the new resource.

在这里,我们要做的不仅仅是在响应中返回创建的Student我们还将响应一个语义清晰的HTTP状态,如果创建成功,还将响应一个指向新资源的URI。

4. Read

4.阅读

As previously mentioned, if we want to read a single Student, it’s more semantically clear to return a 404 if we can’t find the student:

如前所述,如果我们想读取一个单一的Student,如果我们找不到这个学生,返回404的语义会更清晰。

@GetMapping("/{id}")
public ResponseEntity<Student> read(@PathVariable("id") Long id) {
    Student foundStudent = service.read(id);
    if (foundStudent == null) {
        return ResponseEntity.notFound().build();
    } else {
        return ResponseEntity.ok(foundStudent);
    }
}

Here we can clearly see the difference from our initial read() implementation.

在这里,我们可以清楚地看到与我们最初的read()实现的区别。

This way, the Student object will be properly mapped to the response body and returned with a proper status at the same time.

这样一来,Student对象将被正确地映射到响应体中,并同时以适当的状态返回。

5. Update

5.更新

Updating is very similar to creation, except it’s mapped to PUT instead of POST, and the URI contains an id of the resource we’re updating:

更新与创建非常相似,只是它被映射到PUT而不是POST,而且URI包含我们要更新的资源的id

@PutMapping("/{id}")
public ResponseEntity<Student> update(@RequestBody Student student, @PathVariable Long id) {
    Student updatedStudent = service.update(id, student);
    if (updatedStudent == null) {
        return ResponseEntity.notFound().build();
    } else {
        return ResponseEntity.ok(updatedStudent);
    }
}

6. Delete

6.删除

The delete operation is mapped to the DELETE method. The URI also contains the id of the resource:

删除操作被映射到DELETE方法。URI还包含资源的id

@DeleteMapping("/{id}")
public ResponseEntity<Object> deleteStudent(@PathVariable Long id) {
    service.delete(id);
    return ResponseEntity.noContent().build();
}

We didn’t implement specific error handling because the delete() method actually fails by throwing an Exception.

我们没有实现具体的错误处理,因为delete()方法实际上抛出了一个Exception.而失败。

7. Conclusion

7.结论

In this article, we learned how to consume and produce JSON content in a typical CRUD REST service developed with Spring Boot. Additionally, we demonstrated how to implement proper response status control and error handling.

在这篇文章中,我们学习了如何在用Spring Boot开发的典型CRUD REST服务中消费和生产JSON内容。此外,我们还演示了如何实现适当的响应状态控制和错误处理。

To keep things simple, we didn’t go into persistence this time, but Spring Data REST provides a quick and efficient way to build a RESTful data service.

为了保持简单,我们这次没有进入持久化,但是Spring Data REST提供了一种快速而有效的方法来构建RESTful数据服务。

The complete source code for the example is available over on GitHub.

该示例的完整源代码可在GitHub上找到