0

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"

Guy Assaf
  • 888
  • 9
  • 24
  • I think the best design approach is returning Data Transfer Objects (DTO) in your controllers. In this way, you can implement multiple DTOs and each of them only contains fields that are necessary for that endpoint. For example, the getBookOnlyName method should return a BookTitleDto with only one field called name. – Nariman Esmaiely Fard May 21 '20 at 11:51

1 Answers1

0

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.

David Siegal
  • 4,518
  • 2
  • 17
  • 15
  • In my case I do need custom serializer, I need to check some parameters and decide how to serialize the object. – Guy Assaf May 22 '20 at 11:44
  • In that case, see https://stackoverflow.com/a/29103449/937230 But also see the author's follow up note on the drawbacks. – David Siegal May 22 '20 at 20:09