【问题标题】:Spring Boot 2.2.5 get post request parametersSpring Boot 2.2.5 获取post请求参数
【发布时间】:2020-03-27 08:04:19
【问题描述】:

有没有一种方法可以在不为每个请求使用 POJO 对象的情况下获取请求正文(JSON)参数? 我有两种类型的请求,在其中许多请求中,我想要的是从请求中获取参数, 例如这样的:

{"name": "Mike", "Age":25}
request.getBodyParameter("name");

对于我的一些请求,我想将输入 json 转换为 JAVA 哈希映射。

【问题讨论】:

  • 这不是请求参数,而是 JSON 正文。所以不,你不能这样做,你需要将它转换为对象或地图并从那里获取它。
  • 所以对于我的项目中包含 json 作为正文的每个 post 请求,我需要创建一个 POJO 来传输数据?
  • 那个或者创建一个包含结构的地图。
  • 我是spring新手,能给我个链接或例子吗?
  • @mhndev 我已经用你拥有的库更新了答案。

标签: java json spring-boot http


【解决方案1】:
@RequestMapping(value = "/foo", method = RequestMethod.POST, consumes = "application/json")
public Status getJsonData(@RequestBody JsonObject jsonData){
}

来自jsonData 你可以做jsonData.getString("name") 或者你可以把它转换成地图

HashMap<String,Object> result =
        new ObjectMapper().readValue(jsonData, HashMap.class);

更新

 public Status getJsonData(@RequestBody JsonNode jsonNode){
   String name = jsonNode.get("name").asText();
}

转换成地图

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> result = mapper.convertValue(jsonNode, new TypeReference<Map<String, Object>>(){});

【讨论】:

  • 我在我的项目中使用 Jackson for Json,我认为这是 Spring Boot 中的默认 Json Lib,我的项目中没有 JsonObject 类。您能建议使用 Jackson 的其他解决方案吗?
  • 尝试 JsonNode 类
【解决方案2】:

使用JsonNode获取动态对象;

这里是例子

   @PostMapping("/mapping")
    public String getDynamicData(@RequestBody JsonNode jsonNode) {
        String name = jsonNode.get("name").asText();
        return name;
    }

【讨论】:

    【解决方案3】:

    如果您想将 JSON 转换为 controller 中的 hashmap,则以下解决方案将有效。 ObjectConvetore reduce your performance. It's an extra conversion

    @ResponseStatus(HttpStatus.ACCEPTED)
    @RequestMapping(value = "/hi", method = RequestMethod.POST, consumes = "application/json")
    public void startMartExecution(@RequestBody(required = true) Map<String,String> martCriterias) {
            System.out.println(martCriterias.get("name"));
    }
    

    如果你打电话给restAPI from your application,那么下面的代码就可以了。

    HttpHeaders headers = new HttpHeaders();
    RestTemplate restTemplate = new RestTemplate();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Collections.singletonList(MediaType.ALL));
    HttpEntity<Void> entity = new HttpEntity<Void>(null, headers);
    Map<String, Object> body = new HashMap<>();
    ParameterizedTypeReference<Map<String, Object>> parameterizedTypeReference = new ParameterizedTypeReference<Map<String, Object>>() {};
    ResponseEntity<Map<String, Object>> result = restTemplate.exchange(URL, HttpMethod.GET, entity, parameterizedTypeReference);
    body = result.getBody();
    

    谢谢

    【讨论】:

    • 谢谢 Birju,现在我有了哈希图。
    • 您应该在 requestbody 本身中使用 hashmap,因为它支持这种转换,并且可以在时间和大小上提高您的性能。
    • 我可以在我的方法参数中多次使用@requestBody 吗?
    • 不,但是你想这样做吗?
    • 我想让请求既作为我的实体又作为 Json 对象
    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 2015-11-06
    • 2018-07-18
    • 2016-04-06
    • 2022-11-19
    • 2022-11-28
    相关资源
    最近更新 更多