Is there a way to get request body(JSON) parameters without using a POJO object for each request? I have two types of requests, in many of these request what I want is get a parameter from request, for example something like this:
{"name": "Mike", "Age":25}
request.getBodyParameter("name");
and for some of my requests I want to convert the input json to a JAVA hash map.
@RequestMapping(value = "/foo", method = RequestMethod.POST, consumes = "application/json")
public Status getJsonData(@RequestBody JsonObject jsonData){
}
from jsonData
yo can do jsonData.getString("name")
or you can convert this into map
HashMap<String,Object> result =
new ObjectMapper().readValue(jsonData, HashMap.class);
Update
public Status getJsonData(@RequestBody JsonNode jsonNode){
String name = jsonNode.get("name").asText();
}
For conversion to map
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> result = mapper.convertValue(jsonNode, new TypeReference<Map<String, Object>>(){});
Use JsonNode
to take dynamic object;
Here is example
@PostMapping("/mapping")
public String getDynamicData(@RequestBody JsonNode jsonNode) {
String name = jsonNode.get("name").asText();
return name;
}
If you want to convert JSON into hashmap in controller
than below solution will work. 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"));
}
If you call restAPI from your application
thn below code will work.
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();
Thank You
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.