2

I wanted to expose (though Controller) some specific fields of my Entity (let say Person), which has let say:

  • id
  • name
  • number
  • ...

And I wanted to prepare my REST controller, so it will return array of objects - but only id and name of objects:

[
  {
    "name": "name1",
    "id": 1
  },
  {
    "name": "name2",
    "id": 2
  }
  ...
]

I found something similar - Spring Rest Controller Return Specific Fields however the code behind it, is not looking well:

public @ResponseBody List<Map<String, Object>> getAll() {
    List<Person> allPersons = personService.findAll();

    List<Map<String, Object>> resultCollection = new ArrayList<Map<String, Object>>();
    for (Person person : allPersons) {
        Map<String, Object> personValuesMap = new HashMap<String, Object>();
        personValuesMap.put("id", person.getId());
        personValuesMap.put("name", person.getName());
        resultCollection.add(personValuesMap);
    }
    return resultCollection;
}

Is there any more beauty/clear/spring way to achieve this?

1

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy