我的问题是来自URI-String的实体的反序列化。
当我使用by Spring Data Rest生成的HTTP接口时,一切正常。
我可以针对我的端点/api/shoppingLists
发布以下JSON,并将其反序列化为以admin为所有者的购物清单。
{
"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"
}
My 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建议)?
要利用Spring Data REST的设置,消息转换器,异常处理等,请使用@RepositoryRestController注释而不是标准的Spring MVC @Controller或@RestController
有关完整的源代码,请查看GitHub repo
答案 0 :(得分:1)
要使用HAL MessageConverter,您应该将Resource作为参数。尝试将代码更改为:
public PersistentEntityResource postShoppingList(@RequestBody Resource<ShoppingList> shoppingList)
答案 1 :(得分:0)
在我的情况下,问题是pojo的字段名称和json字段之间的差异。即:
@Entity
public class Pojo{
@ManyToOne(fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
@JoinColumn(name = "fk_myother")
public Other myOther;
...etc
}
POST -> /dao/pojos
{
"myother":"http://localhost:8034/dao/others/50"
}
请注意json字段应该是“ myOther ”。
希望这对某人有帮助。