代码之家  ›  专栏  ›  技术社区  ›  Pasha

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

  •  0
  • Pasha  · 技术社区  · 7 年前

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

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

    我使用 元组 在这种方法中。

        @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;
       }
    

    我应该传入的json的结构是什么 PUT 要求

    1 回复  |  直到 7 年前
        1
  •  0
  •   Pasha    7 年前

    我找到了一个方法。 在本例中,它是以下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
    }