How to conditionally serialize with JAXB or Jackso

2019-02-24 17:46发布

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.

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());

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.

2条回答
狗以群分
2楼-- · 2019-02-24 18:03

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>

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

查看更多
别忘想泡老子
3楼-- · 2019-02-24 18:10

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

EclipseLink JAXB (MOXy) offers an external mapping file. This mapping file can augment or completely replace the metadata supplied via annotations. Below is an example where the same object model is mapped to two different weather services (Google and Yahoo)

MOXy also supports both XML and JSON binding:

MOXy also integrates easily with JAX-RS implementations:

查看更多
登录 后发表回答