Spring Data Rest:来自URI的RepositoryRestController反序列化不起作用

Yan*_*lem 7 java spring jackson spring-data spring-data-rest

我的问题是来自URI-String的实体的反序列化.当我使用by Spring Data Rest生成的HTTP接口时,一切正常.我可以针对我的端点发布以下JSON /api/shoppingLists,并将其反序列化为以admin为所有者的购物清单.

{
  "name":"Test", 
  "owners":["http://localhost:8080/api/sLUsers/admin"]
Run Code Online (Sandbox Code Playgroud)

}

当我使用自定义RepositoryRestController时,这不再起作用.如果我将完全相同的JSON发布到同一个端点,我会收到此响应.

{
  "timestamp" : "2015-11-15T13:18:34.550+0000",
  "status" : 400,
  "error" : "Bad Request",
  "exception" : "org.springframework.http.converter.HttpMessageNotReadableException",
  "message" : "Could not read document: Can not instantiate value of type [simple type, class de.yannicklem.shoppinglist.core.user.entity.SLUser] from String value ('http://localhost:8080/api/sLUsers/admin'); no single-String constructor/factory method\n at [Source: java.io.PushbackInputStream@9cad4d2; line: 1, column: 26] (through reference chain: de.yannicklem.shoppinglist.core.list.entity.ShoppingList[\"owners\"]->java.util.HashSet[0]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class de.yannicklem.shoppinglist.core.user.entity.SLUser] from String value ('http://localhost:8080/api/sLUsers/admin'); no single-String constructor/factory method\n at [Source: java.io.PushbackInputStream@9cad4d2; line: 1, column: 26] (through reference chain: de.yannicklem.shoppinglist.core.list.entity.ShoppingList[\"owners\"]->java.util.HashSet[0])",
  "path" : "/api/shoppingLists"
}
Run Code Online (Sandbox Code Playgroud)

我的RepositoryRestController:

@RepositoryRestController
@ExposesResourceFor(ShoppingList.class)
@RequiredArgsConstructor(onConstructor = @__(@Autowired ))
public class ShoppingListRepositoryRestController {

  private final ShoppingListService shoppingListService;

  private final CurrentUserService currentUserService;

  @RequestMapping(method = RequestMethod.POST, value = ShoppingListEndpoints.SHOPPING_LISTS_ENDPOINT)
  @ResponseBody
  @ResponseStatus(HttpStatus.CREATED)
  public PersistentEntityResource postShoppingList(@RequestBody ShoppingList shoppingList,
    PersistentEntityResourceAssembler resourceAssembler) {

    if (shoppingListService.exists(shoppingList)) {
        shoppingListService.handleBeforeSave(shoppingList);
    } else {
        shoppingListService.handleBeforeCreate(shoppingList);
    }

    return resourceAssembler.toResource(shoppingListService.save(shoppingList));
  }
}
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我为什么反序列化不再适用于自定义RepositoryRestController(由文档建议)?

要利用Spring Data REST的设置,消息转换器,异常处理等,请使用@RepositoryRestController注释而不是标准的Spring MVC @Controller或@RestController

有关完整源代码,请查看GitHub仓库

小智 1

为了使用 HAL MessageConverter,您应该有一个 Resource 作为参数。尝试将您的代码更改为:

 public PersistentEntityResource postShoppingList(@RequestBody Resource<ShoppingList> shoppingList)
Run Code Online (Sandbox Code Playgroud)