Select which attributes GET returns from the list in Rest

Asked

Viewed 257 times

0

Ladies and gentlemen, I have the following question. I have an application in Rest that when I ask to return the list, comes with many unnecessary fields, "example below". How do I select the attributes of the Entity class that it should return?

My get:

@GetMapping
public List<Nota> listNotas(){
return notaRepository.findAll();
}

When I get a get I get the following return.

{
    "id": 28,
    "nota": 10,
    "dataNota": [
        2017,
        10,
        10
    ],
    "professor": {
        "id": 1,
        "nome": null,
        "matricula": null,
        "observacao": null,
        "dataNascimento": null,
        "ativo": null
    },
    "materia": {
        "id": 1,
        "nome": null
    },
    "aluno": {
        "id": 1,
        "nome": null,
        "matricula": null,
        "observacao": null,
        "dataNascimento": null,
        "ativo": null,
        "nomeResponsavel": null,
        "foneResponsavel": null
    }
}

I would like you to return with fewer fields as per ex.

{
    "id": 28,
    "nota": 10,
    "dataNota": [
        2017,
        10,
        10
    ],
    "professor": {
        "id": 1,
        "nome": null,
               },
    "materia": {
           "id": 1,
           "nome": null
    },
    "aluno": {
        "id": 1,
        "nome": null,
        "matricula": null,
        }
}
  • In this case, I think the best way would be to create a specific query to return the results you want...

1 answer

0


From a look at http://www.baeldung.com/jackson-json-view-annotation

Basically:

1 - Create a class:

public class Views{
 public static class Public{}
 public static class General extends public{}
}

Whatever is in public, will appear only when public and general what is empublic and general.

2 - in entities note attributes with:

ps:do this in relationships tbm

@JsonView(Views.Public.class) ou @JsonView(Views.General.class)

3 - And finally in getmapping

@GetMapping
@JsonView(Views.Public.class)
public List<Nota> listNotas(){
  return notaRepository.findAll();
}

Browser other questions tagged

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