View Javadoc

1   package com.atlassian.plugins.rest.common.json;
2   
3   import org.codehaus.jackson.JsonEncoding;
4   import org.codehaus.jackson.map.Module;
5   import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
6   import org.codehaus.jackson.map.SerializationConfig;
7   
8   import javax.ws.rs.core.MediaType;
9   import javax.xml.bind.JAXBException;
10  import java.io.ByteArrayOutputStream;
11  import java.io.IOException;
12  import java.util.Collections;
13  
14  public class DefaultJaxbJsonMarshaller implements JaxbJsonMarshaller
15  {
16      private final boolean prettyPrint;
17  
18      public DefaultJaxbJsonMarshaller()
19      {
20          this(false);
21      }
22  
23      public DefaultJaxbJsonMarshaller(boolean prettyPrint)
24      {
25          this.prettyPrint = prettyPrint;
26      }
27  
28      public String marshal(Object jaxbBean)
29      {
30          try
31          {
32              final ByteArrayOutputStream os = new ByteArrayOutputStream();
33              // Don't use JsonGenerator directly as we want to make sure we use the same
34              // configuration as for REST requests in OsgiResourceConfig
35              JacksonJsonProvider jsonProvider = new JacksonJsonProviderFactory().create(Collections.<Module>emptyList());
36              if (prettyPrint)
37              {
38                  jsonProvider.enable(SerializationConfig.Feature.INDENT_OUTPUT, true);
39              }
40              jsonProvider.writeTo(jaxbBean, jaxbBean.getClass(), null, null, MediaType.APPLICATION_JSON_TYPE, null, os);
41              // The encoding used inside JacksonJsonProvider is always UTF-8
42              return new String(os.toByteArray(), JsonEncoding.UTF8.getJavaName());
43          }
44          catch (IOException e)
45          {
46              throw new JsonMarshallingException(e);
47          }
48      }
49  
50      @Deprecated
51      public String marshal(final Object jaxbBean, final Class... jaxbClasses) throws JAXBException
52      {
53          return marshal(jaxbBean);
54      }
55  }