How to cancel @jsonIgnore in specific method

与世无争的帅哥 提交于 2021-01-29 10:52:36

问题


I have a domain javabean, some bean hvae a lot of information with password and login Ip, I use the @jsonIgnore to filter that property which I dont want the end user know.

But there has a problem,In other method I use the same javabean to send back to front side,but now I need some property from this domain has anyway can cancel this @jsonIgnore in some specific method?

@JsonIgnore

private String address;

private Integer drawnum;

but now I need address , I cant do this..... I dont want to use the for loop to add in other object.


回答1:


I think that what you are looking for is the concept of JsonView : in some cases you want a set of attributes to be serialized, and in some other cases you want a (slightly) different set of attributes to be serialized.

Check this excellent tutorial, it explains evrything, even the use with Spring MVC.

Create classes to annotate the fields :

public class Views {
    public static class Public {
    }

    public static class Internal extends Public {
    }
}

Annotate the fields :

public class Item {

    @JsonView(Views.Public.class)
    public int id;

    @JsonView(Views.Public.class)
    public int drawnum;

    @JsonView(Views.Internal.class)
    public String address;
}

In the controller, if you want only "public" properties to be serialized ;

@JsonView(Views.Public.class)
@RequestMapping("/items/{id}")
public Item publicItem(@PathVariable int id) {

Result : {"id":2,"drawnum":5}

In another controller, if you want all properties to be serialized ;

@JsonView(Views.Internal.class)
@RequestMapping("/items/{id}")
public Item internalItem(@PathVariable int id) {

Result : {"id":2,"drawnum":5,"address":"My address"}



来源:https://stackoverflow.com/questions/52528464/how-to-cancel-jsonignore-in-specific-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!