Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading