0

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?

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is there better way to do this? Could I not create a new Java Class that models all of this?
@Richard yes, of course it's possible to create a dedicated class for it, presumably with a constructor filling its own fields from a Data object. And of course it will look better than storing Objects in a map. The question is if such class would ever do anything else - if you can reuse it at multiple locations, if it could do any extra processing (what a Maps can't do), etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.