public static String toJson(
     Object target,
     Type targetType,
     boolean isSerializeNulls,
     Double version,
     String datePattern,
     boolean excludesFieldsWithoutExpose) {
   if (target == null) return EMPTY_JSON;
   GsonBuilder builder = new GsonBuilder();
   if (isSerializeNulls) builder.serializeNulls();
   if (version != null) builder.setVersion(version.doubleValue());
   if (TextUtils.isEmpty(datePattern)) datePattern = DEFAULT_DATE_PATTERN;
   builder.setDateFormat(datePattern);
   if (excludesFieldsWithoutExpose) builder.excludeFieldsWithoutExposeAnnotation();
   String result = EMPTY;
   Gson gson = builder.create();
   try {
     if (targetType != null) {
       result = gson.toJson(target, targetType);
     } else {
       result = gson.toJson(target);
     }
   } catch (Exception ex) {
     if (target instanceof Collection
         || target instanceof Iterator
         || target instanceof Enumeration
         || target.getClass().isArray()) {
       result = EMPTY_JSON_ARRAY;
     } else result = EMPTY_JSON;
   }
   return result;
 }
Example #2
0
 public static void init() {
   if (gson == null) {
     GsonBuilder gsonB = new GsonBuilder();
     gsonB
         .excludeFieldsWithoutExposeAnnotation(); // only fields marked with @Expose will only be
                                                  // considered
     gsonB.registerTypeAdapter(Exception.class, ExceptionTypeAdapter.FACTORY);
     gsonB.registerTypeAdapter(UUID.class, UUIDTypeAdapter.FACTORY);
     gsonB.registerTypeAdapter(
         JsonRequest.class, JsonRequestDefaultToStringDataDeserializer.FACTORY);
     gsonB.setDateFormat("d MMM yyyy"); // "1 Jan 2012"  based on java.text.DateFormat
     gson = gsonB.create();
   }
 }
Example #3
0
 @Provides
 @Singleton
 Gson provideGson() {
   GsonBuilder gsonBuilder = new GsonBuilder();
   gsonBuilder.excludeFieldsWithoutExposeAnnotation();
   //        gsonBuilder.setExclusionStrategies(new ExclusionStrategy() {
   //            @Override
   //            public boolean shouldSkipField(FieldAttributes f) {
   //                return f.getDeclaredClass().equals(ModelAdapter.class);
   //            }
   //
   //            @Override
   //            public boolean shouldSkipClass(Class<?> clazz) {
   //                return false;
   //            }
   //        });
   gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
   return gsonBuilder.create();
 }
Example #4
0
 public static Gson withExpose() {
   GsonBuilder builder = new GsonBuilder();
   builder.excludeFieldsWithoutExposeAnnotation();
   return builder.create();
 }