Answer the question
In order to leave comments, you need to log in
How to convert response from JSON to Java object in Spring Boot?
Good afternoon!
Please do not judge strictly. Let's say there is a GET request that returns data in JSON format. Please explain how can I process this data as a Java object (needed to work with the database) and then return it back to JSON format?
Well, for example, JSON returns the name of the city. I take this city and process it in my database (for example, I compare whether there is such a city in the database) and return the answer in json format. How to do it?
Please, if possible, explain with a simple example in the context of Spring boot RESTful.
Answer the question
In order to leave comments, you need to log in
in the controller in return you return the entity class.
@GetMapping("/myGetsomething")
@Transactional
public meDataClass givebyID(@PathVariable("ID") long id) throws NullPointerException {
try {
return postgresService.giveById(id);//возвращает экземпляр класса @Entity
} catch (NullPointerException e) {
throw new DataNotFoundException();
}
}
Something like this (here without rest, but the difference is minimal). json is received, json is returned. Processing to taste...
@RequestMapping(value = "/some_city/", method = RequestMethod.POST)
public @ResponseBody SomeCity someCity(@RequestParam(value = "somecity", required = true) String somecity) throws Exception {
Gson gson = new Gson();
SomeCity data = gson.fromJson(somecity, SomeCity.class);
return data;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question