【问题标题】:rest api POST request json key mismatchrest api POST 请求 json 密钥不匹配
【发布时间】:2018-12-29 16:25:33
【问题描述】:

我正在使用 Spring Boot Web 模块编写一个普通的发布请求,我的 POST 请求中的字段是名称、描述和标题。

我的问题是,当我使用邮递员或任何客户端发出 POST 请求以添加新实体时,json 键、名称、描述和标题是区分大小写的,但我怎样才能使键不区分大小写。换句话说,即使用户使用 description 而不是 Description 发出发布请求,我的应用程序也应该接受该值,而不是采用 null,因为它不完全匹配。

感谢任何想法

【问题讨论】:

    标签: web-services spring-boot http-post


    【解决方案1】:

    您可以编写函数来检查您的键是否存在区分大小写的值。在get方法中你可以调用方法来选择key。

    public String getIgnoreCase(JSONObject obj, String key) {
    
        Iterator<String> itr = obj.keySet().iterator();
        while (itr.hasNext()) {
            String key1 = itr.next();
            if (key1.equalsIgnoreCase(key)) {
                return obj.get(key1);
            }
        }
        return null;
    }
    

    【讨论】:

    • 感谢您的回复,因为我对 POST 请求使用@RequestBody 注释,如下所示,我究竟可以在哪里使用该功能,例如我的 post 请求可能看起来像 @PostMapping("/add") public ResponseEntity&lt;Void&gt; addNewItem(@RequestBody Item item) { @autowired JpaRepository repository repository.save(item) return ResponseEntity&lt;void&gt; } 但我不知道具体在哪里我可以编写一个验证函数来检查不区分大小写
    • public ResponseEntity> addNewItem(@RequestBody String itemData){ JSONObject obj = new JSONObject(itemData);字符串名称 = obj.optString(getIgnoreCase(obj,"name"));字符串描述 = obj.optString(getIgnoreCase(obj,"description"));字符串标题 = obj.optString(getIgnoreCase(obj,"title"));
    【解决方案2】:

    如果你想保留@RequestBody 项目。那么这里是解决方案:

    在 application.properties 中:

    spring.jackson.mapper.accept_case_insensitive_properties=true
    

    如果你使用 application.yml 那么:

    spring:
      jackson:
        mapper:
          accept_case_insensitive_properties: true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-14
      • 2018-08-04
      • 2018-08-23
      • 2013-05-29
      • 2019-11-25
      • 2019-03-29
      相关资源
      最近更新 更多