'Java Spring custom JSON response

I have a data that looks like so:

{
"name":{
"first": "<firstName>",
"last": "<lastName>" 
},
"info": "<info>",
"place":{
           "location": "<location>",
},
"test": "<test>"
}

However, I want to customize the Response json and group the data by the location. In other words I would like to have a response like this:

"location":[{
            "name": <location>, 
                   user: [{
                         "name": <firstName> + <lastName>, 
                         "info": <info>, 
                         "test": <test>
                         }]
            }]

I have tried to the it into a map like so:

List<Data> data= newArrayList(repository.findAll(Sort.by(Sort.Direction.ASC, "location")));
Map<String, Object> result= new HashMap<>();
for (Data d : data) {
result.put("name",  d.getLocation());
result.put("user", d.getFirstName());

... and so on, but this does not work. What is the best approach to achieve my desired result?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source