Spring Boot 2.2.5获取发布请求参数

时间:2020-03-27 08:04:19

标签: java json spring-boot http

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

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

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

3 个答案:

答案 0 :(得分: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>>(){});

答案 1 :(得分:1)

使用@echo OFF setlocal DISABLEDELAYEDEXPANSION java -jar "stack.jar" -username "stackoverflow" -password %1 -configpath "config.ini" pause 拍摄动态对象;

这里是例子

run.bat my_password

答案 2 :(得分:1)

如果您想在controller中将JSON转换为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();

谢谢