创建后将Spring应用于对象的JsonView吗? [英] Spring apply JsonView to an Object after being created?

查看:59
本文介绍了创建后将Spring应用于对象的JsonView吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个对象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;
}

要动态地应用视图,请将POJO包装到

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆