How to set a custom serializer to ever API endpoint (spring app) with a specific annotation?

437 views Asked by At

let's say I have a controller with an endpoint.

@controller
public class booksController{

  @SomeCustomAnnotation
  public String getBookOnlyName(){
   return new book();
    }


  public String getBookAllData(){
   return new book();
    }
}

In the book object I like to only serialize some fields.

  class book{
    @JsonView(Views.someClass.class)
    public String name;
    public String author;
}

Now I only want to serialize the "name" field from the book instance. And only from endPoint with annotation like "getBookOnlyName"

1

There are 1 answers

2
David Siegal On

By default, properties not explicitly marked as being part of a view are serialized. Consequently, you would only annotate the properties that you want to show conditionally, e.g. with a view named Detailed:

public class Book {
    public String name;

    @JsonView(Views.Detailed.class)
    public String author;
}

Then in your controller, no need for a custom annotation. Just reuse the same annotation, e.g.:

@RestController
public class BooksController {

  public Book getBookSummary() {
    return new Book(...);
  }

  @JsonView(Views.Detailed.class)
  public Book getBookDetail() {
    return new Book(...);
  }
}

Note that in both cases you're still returning a Book; it's just that one will contain fewer properties than the other.

That said, be careful not to use overdo this as it can become a headache in maintaining and properly documenting your API endpoints. Unless you have a dire need to restrict information (e.g. for security purposes), favor a consistent return type, and let your caller ignore what information is not relevant to them.