如何在@RequestBody中传递2个对象?

时间:2018-05-20 01:10:21

标签: java spring spring-mvc model-view-controller

你能帮我解决一下通过@RequestBody传递两个对象的问题吗? 据我所知,您无法传递2个@RequestBody参数,因此我创建了Tuple类来存储自定义数据。 在我的例子中,我需要在json表示中传递Book对象和int值。我已经尝试了不同的方法,但每次都无法正确解析。

    @NoArgsConstructor
    @AllArgsConstructor
    @Getter
    @EqualsAndHashCode
    @ToString
    public final class Tuple<K, V> {
        private K key;
        private V value;
    }

我在此方法中使用Tuple

    @PutMapping("action/returnBook")
    public ResponseEntity<Void> returnBook(@RequestBody final Tuple<Long, Long> userIdBookInstanceId) {
        leasingHistoryService.returnBook(userIdBookInstanceId.getKey(), userIdBookInstanceId.getValue());
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Entity
    @NoArgsConstructor
    @AllArgsConstructor
    @Getter
    @EqualsAndHashCode
    @ToString
    public final class Book {

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

        private String title;

        @ManyToOne(cascade = CascadeType.ALL, optional = false)
        private Author author;

    }

    @Entity
    @NoArgsConstructor
    @AllArgsConstructor
    @Getter
    @EqualsAndHashCode
    @ToString
    public final class Author {

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

        private String name;

        private LocalDate dateOfBirth;

        private String bio;
   }

我应该在PUT请求中传递json的结构是什么?

1 个答案:

答案 0 :(得分:0)

我找到了办法。 在这种情况下,它是以下json:

{
    "key" : {
        "title": "The Girl in the Spider's Web v17",
        "author": {
            "id": 2,
            "name": "Larsson",
            "dateOfBirth": "1954-08-15",
            "bio": "Author of the Millennium trilogy"
        }
    },
    "value": 3
}