我用@JsonView注释了类User,当它返回时,我看到了所有字段,即使不是视图类中包含的字段。这是我的课

@Entity
@Table(name = "users")
public class User implements Serializable{

/**
 *
 */
private static final long serialVersionUID = 1L;
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
private Long userID;
@JsonView(View.Summary.class)
@Column(name="email")
private String email;
@JsonView(View.Summary.class)
@Column(name="user_name")
private String firstName;
@JsonView(View.Summary.class)
@Column(name="user_last_name")
private String lastName;
@JsonView(View.Summary.class)
@Column(name="phone")
private String phone;
@JsonView(View.Summary.class)
@Column(name="origin")
private String address;
@JsonView(View.Summary.class)
@Column(name="birth_date")
private Long birthDate;
@JsonView(View.Summary.class)
@Column(name="gender")
private Long gender;
@JsonView(View.Summary.class)
@Column(name="about_me")
private String aboutMe;
@JsonView(View.SummaryWithPhoto.class)
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name="photo")
private Photo avatar;
@JsonView(View.SummaryWithSession.class)
@Transient
private UserSession session;

//getters and setters


这是我的View课程

public class View {
public interface Summary {}
public interface SummaryWithPhoto extends Summary {}
public interface SummaryWithSession extends SummaryWithPhoto {}
}


因此,然后我请求带有@JsonView(View.SummaryWithPhoto.class)批注的get方法,但我始终会获得userID字段,但不应这样做。这是端点代码

@JsonView(View.SummaryWithPhoto.class)
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<User> getUser(@RequestHeader(value="Access-key") String accessKey,
                                     @RequestHeader(value="Secret-key") String secretKey)

最佳答案

我花了一些调试时间来解决相同的问题。
结果是:


如果不更改此行为,默认情况下将包括所有字段(请参见BeanSerializerFactory.processViews)。要更改默认值,请执行以下操作:

ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);

如果控制器方法用OTHER @JsonView注释,则结果中将省略由@JsonView标记的字段(请参见FilteredBeanPropertyWriter.serializeAsField


因此,对于您的用例,请勿更改默认设置,请通过Long userID注释@JsonView,并通过任何其他(不同的)视图注释getUser

代码com\fasterxml\jackson\core\jackson-databind\2.8.4\jackson-databind-2.8.4-sources.jar!\com\fasterxml\jackson\databind\MapperFeature.java

   * Feature is enabled by default.
   */
   DEFAULT_VIEW_INCLUSION(true)


与博客https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring相矛盾,因此我必须仔细研究一下代码。

08-06 07:23
查看更多