【问题标题】:can we create a single rest API(single endpoint) which can handle different request structures (JSON) in spring boot?我们可以创建一个可以在 Spring Boot 中处理不同请求结构(JSON)的 REST API(单个端点)吗?
【发布时间】:2021-03-01 20:17:41
【问题描述】:

我有一个要求,其中一个休息 API 必须处理不同的请求 json(30 多个不同的请求)。客户端可以发送任何 json 到这个端点,这个 API 应该能够处理请求。而且每个请求都会有唯一的 id。

例如: 请求 1:

{ “身份证”:“1”, “姓名”:“约翰”,

}

请求 2:

{ “身份证”:“2”, “姓名”:“约翰”, "姓氏":"cena", “性”:“F”,

}

请求 3:

{ “身份证”:“3”, "mobileNumber":"09XXXXXXX0", "电子邮件":"nick@yahoo.com",

}

请求 4:

{ “身份证”:“4”, “宠物狗”, “颜色:黑色”, “性”:“F”,

}

现在,如何读取这个 API 的 requestBody?我们可以像下面这样使用 JSONObject 或 JsonNode 吗?

@PostMapping("/save-details")
public String postDetails(@RequestBody JSONObject request) {
    return "";
}

@PostMapping("/save-details")
public String postDetails(@RequestBody JsonNode request) {
    return "";
}

提前感谢您的帮助!

【问题讨论】:

    标签: java spring spring-boot microservices rest


    【解决方案1】:

    一个简单的解决方案是将请求作为 json 字符串接受并使用 Object mapper 转换为所需的类型。

    【讨论】:

      【解决方案2】:

      转换和动态输入正文的示例

      package com.example.springmultirequest;
      
      import org.json.JSONObject;
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import org.springframework.http.ResponseEntity;
      import org.springframework.web.bind.annotation.PostMapping;
      import org.springframework.web.bind.annotation.RequestBody;
      import org.springframework.web.bind.annotation.RestController;
      
      import java.util.Map;
      
      @RestController
      public class DetailController {
      
          Logger logger = LoggerFactory.getLogger(DetailController.class);
      
          @PostMapping("/save-details")
          public ResponseEntity<String> postDetails(@RequestBody Map<String, Object> request) {
      
              JSONObject jsonObject = new JSONObject(request);
              Integer idRequest = Integer.valueOf(jsonObject.get("Id").toString());
              logger.info("idRequest: {}", idRequest);
      
              switch (idRequest) {
                  case 1:
                      logger.info("Name: {}", jsonObject.get("name"));
                      break;
                  case 2:
                      logger.info("Name: {}", jsonObject.get("name"));
                      logger.info("Last name: {}", jsonObject.get("lastname"));
                      break;
                  case 3:
                      logger.info("mobileNumber: {}", jsonObject.get("mobileNumber"));
                      logger.info("email: {}", jsonObject.get("email"));
                      break;
                  case 4:
                      logger.info("pet: {}", jsonObject.get("pet"));
                      logger.info("color: {}", jsonObject.get("color"));
                      logger.info("sex: {}", jsonObject.get("sex"));
                      break;
                  default:
                      return ResponseEntity
                              .badRequest()
                              .body("Identification not recognized");
              }
      
              return ResponseEntity.ok().build();
          }
      }
      

      示例响应:

            .   ____          _            __ _ _
           /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
          ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
           \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
            '  |____| .__|_| |_|_| |_\__, | / / / /
           =========|_|==============|___/=/_/_/_/
           :: Spring Boot ::                (v2.4.3)
          o.s.web.servlet.DispatcherServlet        : Completed initialization in 0 ms
          2021-02-27 12:52:37.406  INFO 17984 --- [nio-8080-exec-1] c.e.springmultirequest.DetailController  : idRequest: 1
          2021-02-27 12:52:37.406  INFO 17984 --- [nio-8080-exec-1] c.e.springmultirequest.DetailController  : Name: john
          2021-02-27 12:52:37.622  INFO 17984 --- [nio-8080-exec-6] c.e.springmultirequest.DetailController  : idRequest: 2
          2021-02-27 12:52:37.622  INFO 17984 --- [nio-8080-exec-6] c.e.springmultirequest.DetailController  : Name: john
          2021-02-27 12:52:37.622  INFO 17984 --- [nio-8080-exec-6] c.e.springmultirequest.DetailController  : Last name: cena
          2021-02-27 12:52:37.676  INFO 17984 --- [nio-8080-exec-8] c.e.springmultirequest.DetailController  : idRequest: 3
          2021-02-27 12:52:37.676  INFO 17984 --- [nio-8080-exec-8] c.e.springmultirequest.DetailController  : mobileNumber: 09XXXXXXX0
          2021-02-27 12:52:37.676  INFO 17984 --- [nio-8080-exec-8] c.e.springmultirequest.DetailController  : email: nick@yahoo.com
          2021-02-27 12:52:37.738  INFO 17984 --- [nio-8080-exec-5] c.e.springmultirequest.DetailController  : idRequest: 4
          2021-02-27 12:52:37.738  INFO 17984 --- [nio-8080-exec-5] c.e.springmultirequest.DetailController  : pet: dog
          2021-02-27 12:52:37.738  INFO 17984 --- [nio-8080-exec-5] c.e.springmultirequest.DetailController  : color: black
          2021-02-27 12:52:37.738  INFO 17984 --- [nio-8080-exec-5] c.e.springmultirequest.DetailController  : sex: F
      

      【讨论】:

        【解决方案3】:

        使用@RequestBody Map 请求读取您的json,通过Json 解析器(如Gson 或Jackson)解析您的json。

        【讨论】:

          【解决方案4】:

          你可以用这个

          @PostMapping(value = "/example" )
          public void abc(@RequestBody HashMap<String, String > requestData) {
          
              System.out.println(requestData);
          
          }
          

          【讨论】:

            猜你喜欢
            • 2018-04-04
            • 2016-08-15
            • 2020-04-22
            • 2023-03-27
            • 1970-01-01
            • 2021-10-14
            • 2023-04-02
            • 1970-01-01
            • 2018-07-23
            相关资源
            最近更新 更多