杰克逊的JSON View课程是什么?它是如何工作的? [英] What is the JSON View class in Jackson and how does it work?

查看:105
本文介绍了杰克逊的JSON View课程是什么?它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白Jackson的@JsonView( Views.MyClass.class )是什么。
我知道我可以用这种方式注释POJO的字段和方法过滤未注释的以免被JSON序列化。但什么是Views.Myclass类?它是Jackson库的模板类吗?

I don't understand what is Jackson's @JsonView(Views.MyClass.class). I know that I can annotate POJO's fields and methods in this way to filter non-annotated ones from being serialized with JSON. But what is the Views.Myclass class? Is it a template class for Jackson library?

为什么Views类中有很多类?例如:

And why can there be many classes inside the Views class? For example like this:

 class Views {
            static class Public { }
            static class ExtendedPublic extends PublicView { }
            static class Internal extends ExtendedPublicView { }
  }

为什么需要以及它是如何工作的?

Why is it needed and how does it work?

推荐答案

使用 @JsonView 来过滤字段取决于序列化的上下文。将数据返回到REST客户端时,根据调用的REST服务,我们需要限制在使用相同数据模型时将序列化哪些数据。

Use @JsonView to filter fields depending on the context of serialization. When returning data to a REST client, depending on which REST service was called, we need to limit which data will be serialized while using the same data model.

让我们说想要创建两个REST服务:

Lets say we want to create two REST services:

第一个服务返回一些用户信息,如名字和姓氏,但不包含附加到它的消息。

The first service returns some user information like first name and last name but not the messages attached to it.

第二个服务返回第一个服务的所有信息以及附加到当前用户的消息。

The second service returns all information from the first service and also the messages attached to the current user.

带有<$ c的示例POJO类$ c> @JsonView 注释

@JsonView(User.Views.Public.class)
    public String getFirstname() {
        return firstname;
    }

 @JsonView(User.Views.Public.class)
    public String getLastname() {
        return lastname;
    }



消息Pojo类



Message Pojo class

@JsonView(User.Views.Internal.class)
    public List<Message> getMessages() {
        return messages;
    }



休息控制器



Rest controller

@RestController
public class SimpleRestController {

    @Autowired
    SimpleService simpleService;

    @RequestMapping(value = "/user/public", method = RequestMethod.GET)
    @JsonView(User.Views.Public.class)
    public User getUserWithPublicData() {
        return simpleService.loadUser();
    }


    @RequestMapping(value = "/user/internal", method = RequestMethod.GET)
    @JsonView(User.Views.Internal.class)
    public User getUserWithInternalData() {
        return simpleService.loadUser();
    }
}

这篇关于杰克逊的JSON View课程是什么?它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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