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.
source share