Jackson @JsonView注解自定义返回POJO类的字段

栏目: Java · 发布时间: 8年前

内容简介:Jackson @JsonView注解自定义返回POJO类的字段

Jackson在Spring框架中可以用来将数据以JSON的格式返回给客户端, @JsonView 注解可以作用在POJO类的属性上,用来自定义返回的类的字段,比如一个用户类,有时只需要返回ID,有时却需要返回ID和姓名:

public class User {
    public interface IDView {};
    public interface IDAndNameView extends IDView {};

    @JsonView(IDView.class)
    private Integer ID;

    @JsonView(IDAndNameView.class)
    private String name;
}

在定义的 @Controller 里面可以这样使用:

@JsonView(User.IDView.class)
@RequestMapping("/id")
public @ResponseBody User getUserID() {
    User user = new User;
    user.setID(1);
    user.setName("Sj");
    return user;
}

以上代码只会返回User对象的ID属性。 @JsonView 可以定义一个需要返回字段的组合。在User对象中,定义了 IDViewIDANdNameView 两个字段组合,然后在 @Controller 的方法上使用同样的 @JsonView 注解,该方法就会返回指定组合的字段。同时,User对象中的 IDAndNameView 继承于 IDView ,所以在方法上使用 @JsonView(IDAndNameView) 注解会同时返回User对象中 IDView 组合中的字段。


以上所述就是小编给大家介绍的《Jackson @JsonView注解自定义返回POJO类的字段》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Convergence Culture

Convergence Culture

Henry Jenkins / NYU Press / 2006-08-01 / USD 30.00

"Convergence Culture" maps a new territory: where old and new media intersect, where grassroots and corporate media collide, where the power of the media producer, and the power of the consumer intera......一起来看看 《Convergence Culture》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具