【问题标题】:How to pass 2 objects in @RequestBody?如何在@RequestBody 中传递 2 个对象?
【发布时间】:2018-05-20 01:10:21
【问题描述】:

你能帮我解决一个通过@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的结构是什么?

【问题讨论】:

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


【解决方案1】:

我找到了一种方法。 在这种情况下,它是以下 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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    相关资源
    最近更新 更多