拨打电话时,如何设置一个可选的RequestBody字段而不将其删除? [英] How can I set an optional RequestBody field without it being deleted when I make the call?

查看:112
本文介绍了拨打电话时,如何设置一个可选的RequestBody字段而不将其删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在spring-boot中有一个小程序,通过一个带有@RequestBody的get调用,它会向我返回一条具有所有规格的消息(以汽车为例)

I have a small program in spring-boot which through a get call having a @RequestBody returns me a message with all the specifications (in my case of cars)

public class CarsRequest implements Serializable {
    private String name;
    private String plate ;
    private  String price;
}

我希望能够确保,如果将一个字段设置为null,它仍然可以找到其他字段具有值的相对消息,在我的情况下,我想说的是名称"字段在RequestBody中是可选的,可以这样做吗?我尝试设置

I would like to be able to make sure that if a field is set to null, it can still find the relative message with the other fields having a value, in my case, I wanted to put that the "name" field is optional in the RequestBody, is it possible to do this? I tried setting

    public CarsResponse getCars(@RequestBody (required = false) CarsRequest request) throws IOException {
           //some code 

   }

但是当我去执行get时,它会在获取时完全删除null字段,因此无法执行

but then when I go to do the get it completely deletes the null field at the time of the get and therefore fails to do it

推荐答案

只需从函数中删除 @RequestBody 批注并保持原样

Just remove the @RequestBody annotation from the function and keep it as it is

public CarsResponse getCars(CarsRequest request) throws IOException {
           //some code 

}

现在所有字段都将转换为查询参数,并且所有字段都是可选的,因为按惯例查询参数是可选的

Now all fields will be converted into query params and all will be optional, because query param by convention are optional

public class CarsRequest implements Serializable {
    private String name;
    private String plate ;
    private  String price;
}

然后这样打电话

GET /someEndpoint?name=<value>&plate=null

但是,如果您仍然想强制使用某些参数,则可以使用 javax.annotations 或自己进行验证.

But still if you want to make some params mandatory, then use javax.annotations or apply validation yourself.

如评论中的要求,如果您接受JSON作为参数主体,则可以做一件事,可以将其接受为String,然后将json转换为函数主体中的对象

As asked in comment, if you are accepting JSON as parameter body then you can do one thing, you can accept it as String and then convert json to object inside function body

public CarsResponse getCars(@RequestParam(required = false) String request) throws IOException {
           ObjectMapper mapper = new ObjectMapper();
           CarRequest request = mapper.readValue(request,CarRequest.class);
          // other code

}

并这样称呼它

GET /someEndpoint?request="{ \"name\" : null, \"plate\": \"someValue\" }"

如果您想继续发送json并将其转换为对象,可以做一件事,您可以声明一个类似这样的活页夹

You can do one more thing if you want to keep sending json and have it transformed into object, you can declare a binder something like this

// Some controller class
class SomeController {
   @Autowired
   ObjectMapper mapper;
   
   // Ommited methods here
   
    @GetMapping("/carRequest")
    public ResponseEntity<String> testBinder(@RequestParam CarRequest request) {
        return ResponseEntity.ok("{\"success\": \"" + request.name+ "\"}");
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(CarRequest.class, new CarRequestEditor(mapper));
    }

    static class CarRequestEditor extends PropertyEditorSupport {

        private ObjectMapper objectMapper;

        public CarRequestEditor(ObjectMapper objectMapper) {
            this.objectMapper = objectMapper;
        }

        @Override
        public void setAsText(String text) throws IllegalArgumentException 
        {
            if (StringUtils.isEmpty(text)) {
                setValue(new CarRequest());
            } else {
                try {
                    setValue(objectMapper.readValue(text, CarRequest.class));
                } catch (JsonProcessingException e) {
                    throw new IllegalArgumentException(e);
                }
            }
        }
    }
   
}

请注意,客户端需要发送这样编码的json URL

Please note that the client need to send the json URL encoded like this

http://localhost:8180/carRequest?request=%7B%22name%22%3"test"%7D

这篇关于拨打电话时,如何设置一个可选的RequestBody字段而不将其删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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