【问题标题】:Spring Hateoas Deserialize Links in Payload to actual EntitiesSpring Hateoas 将有效负载中的链接反序列化到实际实体
【发布时间】:2016-08-06 12:11:42
【问题描述】:

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

@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");
  }
}

部门主管

@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 在反序列化期间无法处理链接。我需要配置/实现什么才能使其正常工作?

谢谢!

【问题讨论】:

  • 您自己对此负责。您可以查看 Spring Data REST。

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


【解决方案1】:

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

原来是这样:

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

还有DepartmentController是什么样子的?

【讨论】:

  • 我添加了部门控制器,但是这个问题不是关于序列化,而是关于链接的反序列化。 ResponseEntity 工作正常(顺便说一句,它是 HttpEntity 的子类)。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2019-01-14
    • 2015-04-18
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 2016-11-03
    • 2016-08-06
    相关资源
    最近更新 更多