简体   繁体   中英

Returns an object list in a get Spring Boot request

I created a Spring service to return a list of notifications to the Front End. However, to make handling the return list easier, I needed to change the return object. But I don't know how to do this.

Currently the return list looks like this:

 [ { "id": 24, "titulo": "Titulo da Notificacao", "mensagem": "Mensagem da Notificacao", "dataCriacao": "2021-07-23 17:00:25.244-03", "dataModificacao": null, "status": true }, { "id": 25, "titulo": "Titulo da Notificacao 2", "mensagem": "Mensagem da Notificacao 2", "dataCriacao": "2021-07-23 17:00:25.244-03", "dataModificacao": null, "status": true } ]

I need the feedback to be like this:

 { "notificacoes": [ { "id": 24, "titulo": "Titulo da Notificacao", "mensagem": "Mensagem da Notificacao", "dataCriacao": "2021-07-23 17:00:25.244-03", "dataModificacao": null, "status": true }, { "id": 25, "titulo": "Titulo da Notificacao 2", "mensagem": "Mensagem da Notificacao 2", "dataCriacao": "2021-07-23 17:00:25.244-03", "dataModificacao": null, "status": true } ] }

 @RequestMapping(value = "/status/{status}", method = RequestMethod.GET, produces = { "application/json" }) public List<?> findAllByStatus(@PathVariable("status") Boolean status) { return service.findAllByStatus(status); }

Can anyone help me? I thought about creating a Notifications object that contains a Notification List. But I think there is a simpler way to do this...

Olá, Romeu, o problema é que você está devolvendo uma lista, tens que criar uma classe em que dentro dela exista uma lista.

Algo desse tipo:

public class Notificacoes {
    private List<Notificacao> notificacoes = new ArrayList<>();
    
    // Construtores, gets e sets
}

E em seguida chamar no seu controller:

@RequestMapping(value = "/status/{status}", method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<Notificacoes> findAllByStatus(@PathVariable("status") Boolean status) {
    return ResponseEntity.ok(new Notificacoes().getNotificacoes().addAll(service.findAllByStatus(status)));
}

Certamente esta não é a melhor forma de fazer, o ideal seria separar as camadas, mas isto já resolve o seu problema.

How about using a map ?

This would allow you to set the key "notificacoes" and reuse the method you currently have, providing a list of notifications.

@RequestMapping(value = "/status/{status}", method = RequestMethod.GET, produces = { "application/json" })
public Map<String, List<Notification>> findAllByStatus(@PathVariable("status") Boolean status) {
        Map<String, List<Notification>> response = new HashMap<>();
        response.put("notificacoes",  service.getNotifications());
        return response;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM