Nic.Star
Nic.Star

Reputation: 160

Best way to explicitly convert POJO into JSON in Spring RestController

I have an existing REST API in a spring boot project that looks somewhat like this:

@GetMapping(value = "/api/projects")
public List<Project> getProjects() {
    List<Project> projects = projectsRepository.findAll();
    List<Project> processed = processProjects(projects);
    return processed;
}

When this method is called the returned JSON response looks something like this:

{
    "JSON":"[
        {
            "id":"aaa",
            "simple":"SYMBOLIC_VALUE_BBB",
            "nested1":{
                "field1":"SYMBOLIC_VALUE_C1",
                "field2":"nonSymbolicValueC2",
                "field3":"SYMBOLIC_VALUE_C3"
            },
            "nested2":{
                "fieldA":"SYMBOLIC_VALUE_DDD"
            }
         },
         ...
     ]",
     "mode":"application/json"
}

The symbolic values are being translated into a human readable form in the frontend. Everything works fine. But now I also need a second version of this method that does the translation on the backend side. Something like this:

@GetMapping(value = "/api/v2/projects")
public String getProjects() {
    List<Project> projects = projectsRepository.findAll();
    String projectsAsJson = ???
    String processedJson = processProjectsJson(projectsAsJson);
    return processedJson;
}

What would I put where the three Question Marks (???) are? I want to use the same json serialization that is used automagically by the Spring Framework. It should be robust against any configuration changes that may happen in the future.

Thank you very much.

Upvotes: 0

Views: 984

Answers (1)

RUARO Thibault
RUARO Thibault

Reputation: 2850

Add a attribute ObjectMapper in your Controller, use dependency injection to get it, and then use : mapper.writeValueAsString(myObject);

Something like that:

@Autowired
private ObjectMapper mapper;

@GetMapping(value = "/api/v2/projects")
public String getProjects() {
    List<Project> projects = projectsRepository.findAll();
    String projectsAsJson = mapper.writeValueAsString(projects);
    String processedJson = processProjectsJson(projectsAsJson);
    return processedJson;
}

Let me know if it is not working.

Upvotes: 3

Related Questions