Home > front end >  Java Spring custom JSON response
Java Spring custom JSON response

Time:02-05

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?

CodePudding user response:

As of now you have a single result map, which you are then overwriting in the loop, so it will contain data for a location only, the last one. What you probably wanted to do is creating a list of those maps, which requires creating a new map inside the loop, and collecting them in a list:

List<Map<String, Object>> result=new ArrayList<>();
for(Data d : data) {
  Map<String, Object> item = new HashMap<>();
  item.put("name", d.getLocation());
  item.put("user", d.getFirstName());
  ...
  result.add(item);
}
  •  Tags:  
  • Related