View Javadoc
1   package ejava.examples.ejbwar.jaxrs;
2   
3   import java.io.InputStream;
4   
5   import javax.json.bind.Jsonb;
6   import javax.json.bind.JsonbBuilder;
7   import javax.json.bind.JsonbConfig;
8   import javax.json.bind.config.PropertyNamingStrategy;
9   import javax.ws.rs.ext.ContextResolver;
10  
11  public class JSONUtils implements ContextResolver<Jsonb> {
12      private static JSONUtils instance;
13      private Jsonb jsb;
14          
15      @Override
16      public Jsonb getContext(Class<?> type) {
17          if (jsb==null) {            
18              JsonbConfig config=new JsonbConfig();
19              //config.setProperty(JsonbConfig.FORMATTING, true);
20              config.setProperty(JsonbConfig.PROPERTY_NAMING_STRATEGY, PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES);
21              //config.setProperty(JsonbConfig.NULL_VALUES, true); //helps us spot fields we don't want
22              jsb=JsonbBuilder.create(config);
23          }
24          return jsb;
25      }
26  
27      private static JSONUtils getInstance() {
28          if (instance==null) {
29              instance=new JSONUtils();
30          }
31          return instance;
32      }
33      
34      public static <T> String marshal(T object) {
35          if (object==null) {
36              return "";
37          }
38          
39          Jsonb jsb = getInstance().getContext(object.getClass());
40          String jsonString = jsb.toJson(object);
41          return jsonString;        
42      }
43      
44      public static <T> T unmarshal(String string, Class<T> type) {
45          if (string==null || string.isEmpty()) {
46              return null;
47          }
48          
49          Jsonb jsb = getInstance().getContext(type);
50          T object = (T) jsb.fromJson(string, type);
51          return object;
52      }
53      
54      public static <T> T unmarshall(InputStream is, Class<T> type) {
55          if (is==null) {
56              return null;
57          }
58          
59          Jsonb jsb = getInstance().getContext(type);
60          T object = (T) jsb.fromJson(is, type);
61          return object;
62      }
63      
64  
65  }