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

o7jaxewo  于 2021-07-13  发布在  Java
关注(0)|答案(4)|浏览(344)

我有一个要求,一个restapi必须处理不同的json请求(30多个不同的请求)。客户端可以向这个端点发送任何json,这个api应该能够处理请求。每个请求都有唯一的id。
例如:请求1:
{“id”:“1”,“name”:“john”,
}
请求2:
{“id”:“2”,“name”:“john”,“lastname”:“cena”,“sex”:“f”,
}
请求3:
{“id”:“3”,“mobilenumber”:“09xx0”,“email”:nick@yahoo.com",
}
请求4:
{“id”:“4”,“pet”:“dog”,“color”:“black”,“sex”:“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 "";
}

提前谢谢你的帮助!

o2g1uqev

o2g1uqev1#

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

ztigrdn8

ztigrdn82#

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

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
zqry0prt

zqry0prt3#

用@requestbody map<string,object>request读取json,通过gson或jackson等json解析器解析json。

sqxo8psd

sqxo8psd4#

你可以用这个

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

    System.out.println(requestData);

}

相关问题