创建后将Spring应用于对象的JsonView吗? [英] Spring apply JsonView to an Object after being created?
问题描述
说我有一个对象User:
Say I've got an object User:
@JsonView(User.Activity.class)
String name
@JsonView(User.Activity.class)
int id
String description;
// Realistically there will be a lot more fiels here...
... getters and setters
然后我就去创建一个:
User u = new User();
u.setName("xoxo");
u.setId(1);
u.setDescription("DESCRIPTION....");
dao.save(u);
return u.withJsonView(User.Activity.class); // Is there a way to apply this?
我想将此对象与来自特定JsonView
的字段一起返回给客户端.我该怎么办?
I want to return this object to the client with the fields from a specific JsonView
. How can I do this?
Hashmap hm = new Hashmap();
MappingJacksonValue value = new MappingJacksonValue(user);
value.setSerializationView(User.Activity.class);
hm.put("success", value);
return ResponseEntity.ok(hm); // Returns whole user object :\
这就是我正在做的.即使我只将User.activity.class
视图放在几个字段上, 值 最终还是整个用户对象.然后,我只是以 响应
That is all I'm doing. value ends up being the whole user object, even though I've only put the User.activity.class
view on a couple of fields. I'm then simply returning the hashmap in a responseentity
推荐答案
要应用视图,请使用 @JsonView
批注:
To apply a view, use the @JsonView
annotation on the endpoint method:
@GetMapping
@JsonView(User.Activity.class)
public User getUser() {
User user = new User();
return user;
}
To apply a view dynamically, wrap your POJO into a MappingJacksonValue
:
@GetMapping
public MappingJacksonValue getUser(){
User user = new User();
MappingJacksonValue value = new MappingJacksonValue(user);
value.setSerializationView(User.Activity.class);
return value;
}
有关更多详细信息,请参见这篇文章关于Spring的Jackson集成.
For more details, check this post about Jackson integration in Spring.
这篇关于创建后将Spring应用于对象的JsonView吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!