RepositoryRestController

RepositoryRestController

我的问题是从URI字符串反序列化实体。
当我使用Spring Data Rest生成的HTTP接口(interface)时,一切正常。
我可以针对端点/api/shoppingLists发布以下JSON,并将其反序列化为以admin作为所有者的购物 list 。

{
  "name":"Test",
  "owners":["http://localhost:8080/api/sLUsers/admin"]

}

当我使用自定义的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"
}

我的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));
  }
}

有人可以告诉我为什么自定义RepositoryRestController(由docs建议)不再反序列化吗?



有关完整的源代码,请查看GitHub repo

最佳答案

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

 public PersistentEntityResource postShoppingList(@RequestBody Resource<ShoppingList> shoppingList)

09-03 17:48