如何在@RequestBody中传递2个对象? [英] How to pass 2 objects in @RequestBody?

查看:798
本文介绍了如何在@RequestBody中传递2个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Could you help me to solve a problem with passing two objects through @RequestBody? As far as I know you can't pass 2 @RequestBody parameters, so I've created Tuple class to store custom data. In my case I need to pass a Book object and int value in json representation. I've already tried different ways but each time it cannot be parsed aright.

    @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的结构是什么?

What is the structure of the json that I should pass in the PUT request?

推荐答案

我找到了一种方法. 在这种情况下,它是以下json:

I've found a way to do it. In this case it's the following 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
}

这篇关于如何在@RequestBody中传递2个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆