简体   繁体   English

我们可以在 spring 引导中创建一个可以处理不同请求结构 (JSON) 的 rest API(单端点)吗?

[英]can we create a single rest API(single endpoint) which can handle different request structures (JSON) in spring boot?

I have a requirement where one rest API have to handle different request json(30+ different requests).我有一个要求,其中一个 rest API 必须处理不同的请求 json(30 多个不同的请求)。 the client can send any json to this endpoint and this API should be able to process the request.客户端可以将任何 json 发送到此端点,并且此 API 应该能够处理请求。 And every request will have unique id.每个请求都有唯一的 id。

Ex: Request 1:例如:请求 1:

{ "Id": "1", "name":"john", { “身份证”:“1”,“姓名”:“约翰”,

} }

Request 2:要求 2:

{ "Id": "2", "name":"john", "lastname":"cena", "sex":"F", { "Id": "2", "name":"john", "lastname":"cena", "sex":"F",

} }

Request 3:要求 3:

{ "Id": "3", "mobileNumber":"09XXXXXXX0", "email":"nick@yahoo.com", { "Id": "3", "mobileNumber":"09XXXXXXX0", "email":"nick@yahoo.com",

} }

Request 4:要求 4:

{ "Id": "4", "pet":"dog", "color":"black", "sex":"F", { “ID”:“4”,“宠物”:“狗”,“颜色”:“黑色”,“性别”:“F”,

} }

now, how to read requestBody for this API?现在,如何读取这个 API 的 requestBody? can we use JSONObject or JsonNode like below?我们可以像下面这样使用 JSONObject 或 JsonNode 吗?

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

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

Thanks for the help in Advance!我在这里先向您的帮助表示感谢!

A simple solution would be to accept the request as a json string and the use Object mapper to convert to desired type.一个简单的解决方案是将请求作为 json 字符串接受,并使用 Object 映射器转换为所需的类型。

An example with conversion and dynamically input body转换和动态输入正文的示例

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();
    }
}

Example Response:示例响应:

      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: 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

Read you json with @RequestBody Map<String, Object> request, parse through your json via Json parser like Gson or Jackson. Read you json with @RequestBody Map<String, Object> request, parse through your json via Json parser like Gson or Jackson.

You can use this你可以用这个

@PostMapping(value = "/example" )
public void abc(@RequestBody HashMap<String, String > requestData) {

    System.out.println(requestData);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Spring 引导中将不同的 JSON 响应消耗到客户端的单个端点中? - How to consume different JSON response into a single endpoint for a client in Spring Boot? 我们可以在单个spring boot应用程序中使用多个yaml文件吗? - Can we use multiple yaml files in a single spring boot application? Spring Rest WS:如何在单个端点中处理多个XML有效负载? - Spring Rest WS: How to handle multiple XML payloads in single endpoint? 我们可以在不同的端口上运行 Spring REST API 吗? - Can we run Spring REST API on different ports? 如何在邮递员中将多个字符串包装成单个字符串以调用spring boot rest API Get请求 - How to wrap multiple strings into single string in postman to call spring boot rest API Get request 使用 Spring Boot 找不到 Spring Data Rest Endpoint - Can't find Spring Data Rest Endpoint with Spring Boot Spring MVC在单个HTTP请求中处理多个REST命令 - Spring MVC handle multiple REST commands in a single HTTP request 在Spring Boot Rest Controller中解析Json数组init单个对象 - Parse Json array init single object in Spring boot Rest Controller Spring Boot:发布到REST API会将单个字符串存储为数组 - Spring Boot: Posting to a REST API is storing a single string as an array Spring Boot Actuator - 启用单个端点 - Spring Boot Actuator - enable single endpoint
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM