K
K
KaizerSX2020-01-22 17:39:54
Java
KaizerSX, 2020-01-22 17:39:54

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

2 answer(s)
D
DDwrt100, 2020-01-22
@DDwrt100

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

  }

M
mystifier, 2020-01-22
@mystifier

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 question

Ask a Question

731 491 924 answers to any question