How to conditionally serialize with JAXB or Jackson? Appearance and interior view

I am creating a RESTful API, and I have a use case when I need to be able to display two different views of my data. One that we can use inside, and one that we will exhibit from the outside. In addition, my API must support both XML and JSON.

For my JSON answer, this is very easy to do with Jackson. I can conditionally include fields in my JSON Response using the JsonViews function: http://wiki.fasterxml.com/JacksonJsonViews

First you need to create a simple class that defines your views:

public class Views { public static class External {} public static class Internal extends External {} } 

Now, with my view classes, I just comment on my fields with which they belong like this:

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

Then you 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 it is not currently supported for XML. How can I achieve the same with XML? I am ready to use JAXB if necessary for my XML conversion.

+4
source share
2 answers

I managed to get this working by adding a new library to override the default value:

  <!-- 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 functions. Very clean! The one I added was aalto-xml.

+2
source

Note. I am an EclipseLink JAXB (MOXy) and a member of the JAXB Group (JSR-222) .

EclipseLink JAXB (MOXy) offers an external mapping file. This mapping file may supplement or completely replace the metadata provided through annotations. The following is an example where the same object model is mapped to two different weather services (Google and Yahoo).

MOXy also supports both XML binding and JSON:

MOXy also integrates seamlessly with JAX-RS implementations:

0
source

Source: https://habr.com/ru/post/1440373/


All Articles