0

我有這樣一些控制方法:春HATEOAS反序列化鏈接的有效載荷,以實際實體

@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

​​

而一個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" 
    } 
    } 
} 

現在的問題:當我發送創建請求與有效載荷,傑克遜或彈簧安置/ HATEOAS在反序列化過程中無法處理鏈接。我需要配置/執行什麼才能使其工作?

謝謝!

+0

你有責任爲自己。你可以看看Spring Data REST。 – zeroflagL

回答

0

我覺得這裏應該返回一個HttpEntity而不是ResponseEntity

因此,這將是:

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

還什麼DepartmentController樣子?

+0

我添加了部門控制器,但這個問題不是關於序列化,而是關於鏈接的反序列化。 ResponseEntity正常工作(順便說一下是HttpEntity的一個子類)。 – Benny

0

您發佈的資源類必須與GET端點返回的類不同。它們必須包含識別要關聯資源的元素,而不是您必須自行解決。

如果你看看這個示例項目https://github.com/opencredo/spring-hateoas-sample和專門BookController,你可能會看到一個新的Book是如何發佈和相關Author s的解決