Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonView - define Default View

I am working on a Spring boot (MVC, JPA) application and it is required to return different attributes on different requests. I found the @JsonView annotation and it seems to work. But do I need to annotate every attribute with a basic view?

Example:

Entity1

 @Entity
    public class Entity1 implements Serializable {
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long id;

      @JsonView(JsonViews.ExtendedView.class)
      private String name;

      @OneToMany(cascade = CascadeType.ALL, mappedBy = "entity1", fetch = FetchType.EAGER)
      List<Entity2> entities2;

      @JsonView(JsonView.ExtendedView.class)
      @OneToMany(cascade = CascadeType.ALL, mappedBy = "entity1", fetch = FetchType.LAZY)
      List<Entity3> entities3;

    }

Entity2

@Entity
public class Entity2 implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  private String name;
}

Entity3

@Entity
public class Entity3 implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  private String name;
}

Views

public class JsonViews {
  public static class BasicView { }
  public static class ExtendedView extends BasicView { }
}

Controller

@RequestMapping(method = RequestMethod.GET)
  @JsonView(JsonViews.BasicView.class)
  public @ResponseBody List<Entity1> index() {

    return repositoryEntity1.findAll();

  }

This is a trimmed example but I think it applies to the problem. I expect that the controller returns the Ids and the list of Entity2 objects. But it returns an empty object with "No Properties". If I annotate every attribute of every class involved in this request, it seems to work, but is this really needed or the best solution? Is there a way to define a "DefaultView"?

thanks

Edit: If I annotate the JpaRepository it returns the entire object including the list with Entity3 objects.

like image 515
KenavR Avatar asked Mar 02 '15 15:03

KenavR


1 Answers

No, you do not need to define views on all properties. Insert

spring.jackson.mapper.default-view-inclusion=true

in your application.properties. This will cause properties without the @JsonView annotation to be included in the response and only the annotated properties will be filtered.

In your Controller, properties without a view or with the BasicView annotated will be returned.

like image 191
Zavael Avatar answered Nov 10 '22 05:11

Zavael