spring-bootswagger-uijson-view

Springboot swagger with JsonView


It's possible to integrate the swagger with @JsonView? I have one model that I use the @JsonView to return only a few fields, but the swagger-ui shows the hole model.

This is my model:

public class Intimacao extends EntityBase {
    @Embedded
    @JsonView({View.Intimacao_Lista.class})
    private Devedor devedor;
    @Embedded
    private Sacador sacador;
    @Embedded
    private Apresentante apresentante;
    @Embedded
    private Titulo titulo;

}

This is my controller:

@GetMapping("/")
@PreAuthorize("hasRole('ADMINISTRADOR') or hasRole('MOTOBOY')")
@JsonView({View.Intimacao_Lista.class})
public List<Intimacao> listar(Principal principal){
    System.out.println(principal.getName());
    return null;
}

This is the result in swagger-ui

[
  {
    "apresentante": {
      "documento": "string",
      "nome": "string"
    },
    "devedor": {
      "bairro": "string",
      "cep": "string",
      "cidade": "string",
      "complemento": "string",
      "documento": "string",
      "estado": "string",
      "logradouro": "string",
      "nome": "string",
      "numero": "string",
      "tipoLogradorouo": "string"
    },
    "id": 0,
    "sacador": {
      "chave": "string",
      "documento": "string",
      "especie": "string",
      "nome": "string"
    },
    "titulo": {
      "custas1": 0,
      "custas2": 0,
      "custas3": 0,
      "custas4": 0,
      "custas5": 0,
      "custas6": 0,
      "custas7": 0,
      "custas8": 0,
      "custas9": 0,
      "numero": "string",
      "vencimento": "string"
    }
  }
]

But if I GET my API only will return the devedor properties, because the @JsonView


Solution

  • It's possible to integrate the swagger with @JsonView?

    Yes (partially).

    After this pull request was merged you can use it for:

    Response Objects (you got that part working).

    @GetMapping("/")
    @PreAuthorize("hasRole('ADMINISTRADOR') or hasRole('MOTOBOY')")
    @JsonView({View.Intimacao_Lista.class})
    public List<Intimacao> listar(Principal principal){
        System.out.println(principal.getName());
        return null;
    }
    

    RequestBody Objects (not yet, pull request on its way, see #2918 and an example in comment at #2079). In your case:

    @GetMapping("/")
    @PreAuthorize("hasRole('ADMINISTRADOR') or hasRole('MOTOBOY')")
    @JsonView({View.Intimacao_Lista.class})
    // replace `Views.Principal.class` for the proper value
    public List<Intimacao> listar(@JsonView(Views.Principal.class) Principal principal){
        System.out.println(principal.getName());
        return null;
    }