繁体   English   中英

Spring Boot 2.2.5 获取post请求参数

[英]Spring Boot 2.2.5 get post request parameters

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

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

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

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

使用JsonNode取动态对象;

这是例子

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

如果您想在controller中将 JSON 转换为 hashmap,那么下面的解决方案将起作用。 ObjectConvetore reduce your performance. It's an extra conversion 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调用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();

谢谢你

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM