View Javadoc

1   package com.atlassian.plugins.rest.common.json;
2   
3   import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
4   import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
5   import org.codehaus.jackson.map.AnnotationIntrospector;
6   import org.codehaus.jackson.map.DeserializationConfig;
7   import org.codehaus.jackson.map.Module;
8   import org.codehaus.jackson.map.ObjectMapper;
9   import org.codehaus.jackson.map.SerializationConfig;
10  import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
11  import org.codehaus.jackson.map.introspect.JacksonAnnotationIntrospector;
12  import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
13  
14  import java.util.Collections;
15  
16  public class JacksonJsonProviderFactory
17  {
18      public JacksonJsonProvider create()
19      {
20          return create(Collections.<Module>emptyList());
21      }
22  
23      public JacksonJsonProvider create(Iterable<? extends Module> modules)
24      {
25          ObjectMapper mapper = new ObjectMapper();
26  
27          /* This is what MapperConfigurator would do to a default ObjectMapper */
28          AnnotationIntrospector intr = AnnotationIntrospector.pair(new JacksonAnnotationIntrospector(),  new JaxbAnnotationIntrospector());
29          mapper.setDeserializationConfig(mapper.getDeserializationConfig().withAnnotationIntrospector(intr));
30          mapper.setSerializationConfig(mapper.getSerializationConfig().withAnnotationIntrospector(intr));
31  
32          /* In the absence of a specific annotation for @JsonSerialize(include), ignore null fields when serializing */
33          mapper.setSerializationInclusion(Inclusion.NON_NULL);
34  
35          for (Module module : modules)
36          {
37              mapper.registerModule(module);
38          }
39  
40          JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(mapper, JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS);
41  
42          // Make sure we only rely on annotations for de-/serialization
43          provider.configure(SerializationConfig.Feature.AUTO_DETECT_GETTERS, false);
44          provider.configure(SerializationConfig.Feature.AUTO_DETECT_FIELDS, false);
45          provider.configure(DeserializationConfig.Feature.AUTO_DETECT_SETTERS, false);
46          provider.configure(DeserializationConfig.Feature.AUTO_DETECT_FIELDS, false);
47          return provider;
48      }
49  }