Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我们可以创建一个RESTAPI(单端点)来处理SpringBoot中的不同请求结构(JSON)吗?_Java_Spring_Spring Boot_Microservices_Restapi - Fatal编程技术网

Java 我们可以创建一个RESTAPI(单端点)来处理SpringBoot中的不同请求结构(JSON)吗?

Java 我们可以创建一个RESTAPI(单端点)来处理SpringBoot中的不同请求结构(JSON)吗?,java,spring,spring-boot,microservices,restapi,Java,Spring,Spring Boot,Microservices,Restapi,我有一个要求,一个RESTAPI必须处理不同的json请求(30多个不同的请求)。客户端可以向该端点发送任何json,该API应该能够处理该请求。每个请求都有唯一的id 例: 请求1: { “Id”:“1”, “姓名”:“约翰” } 请求2: { “Id”:“2”, “姓名”:“约翰”, “姓氏”:“cena”, “性”:“F” } 请求3: { “Id”:“3”, “mobileNumber”:“09xxxxxx0”, “电子邮件”:nick@yahoo.com“ } 请求4: { “Id”:

我有一个要求,一个RESTAPI必须处理不同的json请求(30多个不同的请求)。客户端可以向该端点发送任何json,该API应该能够处理该请求。每个请求都有唯一的id

例: 请求1:

{ “Id”:“1”, “姓名”:“约翰”

}

请求2:

{ “Id”:“2”, “姓名”:“约翰”, “姓氏”:“cena”, “性”:“F”

}

请求3:

{ “Id”:“3”, “mobileNumber”:“09xxxxxx0”, “电子邮件”:nick@yahoo.com“

}

请求4:

{ “Id”:“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 "";
}

提前谢谢你的帮助

一个简单的解决方案是将请求作为json字符串接受,并使用对象映射器转换为所需的类型。

您可以使用
@PostMapping(value=“/example”)
public void abc(@RequestBody HashMap requestData){
System.out.println(requestData);
}

带有转换和动态输入体的示例

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

通过@RequestBody-Map-request阅读json,通过Gson或Jackson等json解析器解析json

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