Spring Hateoas将Payload中的链接反序列化为实际实体

时间:2016-04-14 18:51:11

标签: spring-mvc spring-boot jackson spring-hateoas spring-restcontroller

我有一些控制器方法,如:

@RequestMapping(value = "/person", method = RequestMethod.POST)
public ResponseEntity<?> create(@RequestBody Person person) {
  personRepository.save(person);
  return new ResponseEntity<>(HttpStatus.OK);
}

人员有效负载是(链接指向部门的uri):

{
  "name": "Barack Obama",
  "department": "http://localhost:8080/department/1"
}

我有一个PersonResource

public class PersonResource {
  String name;
}

还有一个ResourceAssembler

public class PersonResourceAssembler extends ResourceAssemblerSupport<PersonResource, Person> {
  public PersonResourceAssembler() {
    super(PersonController.class, PersonResource.class);
  }

  @Override
  public PersonResource toResource(Person person) {
    PersonResource res = new PersonResource();
    res.setName(person.getName());
    res.add(linkTo(methodOn(DepartmentController.class).getOne(person.getDepartment().getId())).withRel("department");
  }
}

DepartmentController

@RestController
@RequestMapping("/department")
public class DepartmentController {
  @RequestMapping("/{id}")
  public ResponseEntity<DepartmentResource> getOne(@PathVariable("id") Long id) {
    Department dep = departmentRepository.findOne(id);
    DepartmentResource res = departmentResourceAssembler.toResource(res);
    return new ResponseEntity<>(res, HttpStatus.OK);
  }
}

这将导致json像:

{
  "name": "Barack Obama",
  "_links": {
    "department": {
      "href": "http://localhost:8080/department/1"
    }
  }
}

现在问题:当我发送带有效负载的create-Request时,Jackson或Spring Rest / HATEOAS在反序列化期间无法处理链接。我需要配置/实现什么才能使其正常工作?

谢谢!

2 个答案:

答案 0 :(得分:0)

我想在这里你应该返回一个HttpEntity而不是ResponseEntity

所以它会是:

 @RequestMapping(value = "/person", method = RequestMethod.POST)
public HttpEntity create(@RequestBody Person person) {
  personRepository.save(person);
  return new ResponseEntity<>(HttpStatus.OK);
}

还有DepartmentController的样子?

答案 1 :(得分:0)

您发布的资源类必须与GET端点返回的类不同。它们必须包含用于标识要关联的资源的元素,而不是必须由您自己解决。

如果您查看此示例项目https://github.com/opencredo/spring-hateoas-sample,特别是BookController,您可能会看到如何发布新的Book并解析相关的Author