如何使用JAXB或Jackson有条件地序列化?外部视图与内部视图 [英] How to conditionally serialize with JAXB or Jackson? External View vs Internal View

查看:179
本文介绍了如何使用JAXB或Jackson有条件地序列化?外部视图与内部视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个RESTful API,我有一个用例,我需要能够呈现两个不同的数据视图。我们可以在内部使用的一个,以及我们将在外部公开的一个。另外,我的API需要同时支持XML和JSON。

I'm building a RESTful API and I have a use case where I need to be able to render two different views of my data. One that we can use internally and one that we will expose externally. Additionally my API needs to support both XML and JSON.

对于我的JSON响应,这对Jackson来说非常容易。我可以通过使用JsonViews的功能有条件地在我的JSON响应中包含字段: http://wiki.fasterxml.com/JacksonJsonViews

For my JSON response this is exteremely easy to do with Jackson. I can conditionally include fields in my JSON Response by using the feature of JsonViews: http://wiki.fasterxml.com/JacksonJsonViews

首先,您需要创建一个指定视图的简单类:

First you need to create a simple class specifying your views:

public class Views {

    public static class External {}

    public static class Internal extends External {}
}

现在我的视图类只是注释我的字段,它们属于哪个视图:

Now with my view classes I just annotate my fields with which view they belong to like so:

    @JsonView(Views.External.class)
    private String external = "External";

    @JsonView(Views.Internal.class)
    private String internal = "Internal";

然后,您可以序列化对象并指定要使用的视图:

You then can serialize the object and specify which view you want to use:

    ObjectMapper jsonMapper = new ObjectMapper();
    ObjectWriter externalWriter = jsonMapper.writerWithView(Views.External.class);
    String externalJson = externalWriter.writeValueAsString(new ResponseObject());

这适用于JSON,但不幸的是,目前不支持XML。我如何用XML实现相同的目标?我愿意在必要时使用JAXB进行XML转换。

This works well for JSON but unfortunately the same is currently unsupported for XML. How can I achieve the same with XML? I am willing to use JAXB if necessary for my XML conversion.

推荐答案

我能够通过添加新库来实现这一点覆盖默认值:

I was able to get this working by adding a new library to override the default:

        <!-- Used to Convert our objects to JSON and XML -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.0.6</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.0.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml</groupId>
            <artifactId>aalto-xml</artifactId>
            <version>0.9.8</version>
        </dependency>

现在我可以使用Jackson及其@来序列化为JSON XML JsonView功能。很干净!我添加的是aalto-xml。

So now I can serialize to JSON and XML using Jackson and their @JsonView functionality. Very clean! The one I added was aalto-xml.

这篇关于如何使用JAXB或Jackson有条件地序列化?外部视图与内部视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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