Get a list of objects with custom message (Spring Boot)

Asked

Viewed 27 times

-1

At the moment I can return the list of objects (products).

I would like to show the information of each object with a formatted text, for example:
O produto (nome_produto) tem o preço (preço_produto) que é (descrição_do_produto).

@GetMapping("/list/{id}")
public ResponseEntity<List<Product>> listProducts(@PathVariable long id){

    try {
        Optional<Client> searchClient = clientService.getClientById(id);

        if (searchClient.isPresent()) {
            List<Product> wishlist = wishListService.getWishlist(searchClient.get()).getProduct();

            return new ResponseEntity<>(wishlist,HttpStatus.OK);
        }
        else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

    }catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

}

1 answer

0

Quick and "unusual solution"

You can define which fields will appear on the return of the list with json, and you can even generate new fields.

For this, use @JsonProperty that will return a new property. In this case you can create a get method, concatenate the phrase you want, and the result will be returned in json.

Also use @JsonIgnoreto remove properties that are being returned but you do not want in return.

Understanding the subject

Usually when you build API, or microserviço, and the same is consumed by another system, or by a frontend module, it is not used to format the data to send to the layer or application of view.

In itself front, is that usually the data is formatted to respond in the appropriate way to the user. Although it is not required to work in this way.

But this favors reuse.

Let me give you an example. Imagine a list of books that are returned like this:

...
   [
     {"titulo": "livro 1", editora: "X"},
     {"titulo": "livro 2", editora: "Y"},
     {"titulo": "livro 3", editora: "A"},
     {"titulo": "livro 4", editora: "B"}
   ]

Imagine that your service returns the way above. Two different views devices (2 different applications, for example a mobile application and a web front) can receive this data and format it in the appropriate way.

One can use separate fields. Another can concatenate into a sentence as you proposed.

Let’s say in the mobile app the goal is to display:
livro 1 da editora X

Already on the web front, the goal is to present so:
editora X: livro 1

Therefore, the most appropriate is the return of the data in format JSON, or XML for example with the appropriate values.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.