Spring 数据 REST:"no String-argument constructor/factory method to deserialize from String value"

Spring Data REST: "no String-argument constructor/factory method to deserialize from String value"

当我在 Spring Data REST 应用程序中使用 Lombok 来定义复杂类型时:

@NoArgsConstructor
@AllArgsConstructor
@Data

@Entity
@Table(name = "BOOK")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false)
    private Long id;

    private String title;

    @ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH})
    private Person author;

    // ...
}

使用 Spring 数据 REST 控制器,例如:

@RepositoryRestController
public class BookRepositoryRestController {

    private final BookRepository repository;

    @Autowired
    public BookRepositoryRestController(BookRepository repository) {
        this.repository = repository;
    }

    @RequestMapping(method = RequestMethod.POST,value = "/books")
    public @ResponseBody PersistentEntityResource post(
        @RequestBody Book book,
        PersistentEntityResourceAssembler assembler) {

        Book entity = processPost(book);

        return assembler.toResource(entity);
    }

    private Book processPost(Book book) {
        // ...
        return this.repository.save(book);
    }
}

我收到一个丑陋的错误:

no String-argument constructor/factory method to deserialize from String value

来自 Spring Data REST 对 Jackson 的使用以及一本书 POST 比如:

curl -X POST 
     -H 'content-type: application/json' 
     -d '{"title":"Skip Like a Pro", "author": "/people/123"}'
     http://localhost:8080/api/books/

反序列化错误发生在 Jackson 尝试解析 /people/123 本地 URI 时,该 URI 应该解析为单个唯一的 Person。如果我删除我的 @RepositoryRestController,一切正常。知道我的 REST 控制器定义有什么问题吗?

@RepositoryRestController 中,将 @RequestBody 参数的类型从 Book 更改为 Resource<Book>:

import org.springframework.hateoas.Resource;

    // ...

    @RequestMapping(method = RequestMethod.POST,value = "/books")
    public @ResponseBody PersistentEntityResource post(
        @RequestBody Resource<Book> bookResource,             // Resource<Book>
        PersistentEntityResourceAssembler assembler) {

        Book book = bookResource.getContent()
        // ...
    }

并在 Book 实体定义中将 AllArgsConstructor 注释修改为:@AllArgsConstructor(suppressConstructorProperties = true).

有关详细信息,请参阅 Spring Data REST #687