View Javadoc
1   package ejava.util.json;
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   
10  public class JsonbUtil {
11      static Jsonb getContext(Class<?> type) {
12          JsonbConfig config=new JsonbConfig();
13          //config.setProperty(JsonbConfig.FORMATTING, true);
14          config.setProperty(JsonbConfig.PROPERTY_NAMING_STRATEGY, PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES);
15          //config.setProperty(JsonbConfig.NULL_VALUES, true); //helps us spot fields we don't want
16          return JsonbBuilder.create(config);
17      }
18  
19      public static <T> String marshal(T object) {
20          if (object==null) {
21              return "";
22          }
23          
24          Jsonb jsb = getContext(object.getClass());
25          String jsonString = jsb.toJson(object);
26          return jsonString;        
27      }
28      
29      public static <T> T unmarshal(String string, Class<T> type) {
30          if (string==null || string.isEmpty()) {
31              return null;
32          }
33          
34          Jsonb jsb = getContext(type);
35          T object = (T) jsb.fromJson(string, type);
36          return object;
37      }
38      
39      public static <T> T unmarshall(InputStream is, Class<T> type) {
40          if (is==null) {
41              return null;
42          }
43          
44          Jsonb jsb = getContext(type);
45          T object = (T) jsb.fromJson(is, type);
46          return object;
47      }
48  }