com.google.gson.ExclusionStrategy Java Examples

The following examples show how to use com.google.gson.ExclusionStrategy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MCRPIService.java    From mycore with GNU General Public License v3.0 7 votes vote down vote up
protected static Gson getGson() {
    return new GsonBuilder().registerTypeAdapter(Date.class, new MCRGsonUTCDateAdapter())
        .setExclusionStrategies(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                String name = fieldAttributes.getName();

                return Stream.of("mcrRevision", "mycoreID", "id", "mcrVersion")
                    .anyMatch(field -> field.equals(name));
            }

            @Override
            public boolean shouldSkipClass(Class<?> aClass) {
                return false;
            }
        }).create();
}
 
Example #2
Source File: JSONUtils.java    From pagarme-java with The Unlicense 6 votes vote down vote up
private static GsonBuilder getNewDefaultGsonBuilder(){
    return new GsonBuilder()
        .excludeFieldsWithoutExposeAnnotation()
        .registerTypeAdapter(DateTime.class, new DateTimeIsodateAdapter())
        .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
        .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
        .setExclusionStrategies(new ExclusionStrategy(){

            public boolean shouldSkipClass(Class<?> clazz) {
                return false;
            }

            public boolean shouldSkipField(FieldAttributes fieldAttrs) {
                return fieldAttrs.equals(null);
            }
            
        });
}
 
Example #3
Source File: SerializationWithExclusionsUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenExclusionStrategyByStartsWith_whenSerializing_thenFollowStrategy() {
    MyClass source = new MyClass(1L, "foo", "bar", new MySubClass(42L, "the answer", "Verbose field which we don't want to be serialized"));
    ExclusionStrategy strategy = new ExclusionStrategy() {
        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }

        @Override
        public boolean shouldSkipField(FieldAttributes field) {
            return field.getName().startsWith("other");
        }
    };
    Gson gson = new GsonBuilder().setExclusionStrategies(strategy)
        .create();
    String jsonString = gson.toJson(source);

    assertEquals(expectedResult, jsonString);
}
 
Example #4
Source File: SerializationWithExclusionsUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenExclusionStrategyByCustomAnnotation_whenSerializing_thenFollowStrategy() {
    MyClassWithCustomAnnotatedFields source = new MyClassWithCustomAnnotatedFields(1L, "foo", "bar", new MySubClassWithCustomAnnotatedFields(42L, "the answer", "Verbose field which we don't want to be serialized"));
    ExclusionStrategy strategy = new ExclusionStrategy() {
        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }

        @Override
        public boolean shouldSkipField(FieldAttributes field) {
            return field.getAnnotation(Exclude.class) != null;
        }

    };

    Gson gson = new GsonBuilder().setExclusionStrategies(strategy)
        .create();
    String jsonString = gson.toJson(source);
    assertEquals(expectedResult, jsonString);
}
 
Example #5
Source File: Servicios.java    From ExamplesAndroid with Apache License 2.0 6 votes vote down vote up
public Servicios() {

        Gson gson = new GsonBuilder()
                .setExclusionStrategies(new ExclusionStrategy() {
                    @Override
                    public boolean shouldSkipField(FieldAttributes f) {
                        return f.getDeclaringClass().equals(RealmObject.class);
                    }

                    @Override
                    public boolean shouldSkipClass(Class<?> clazz) {
                        return false;
                    }
                })
                .create();


        this.retrofit = new Retrofit.Builder()
                .baseUrl(ip)//
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        services = retrofit.create(IServices.class);
            //repositoryPhotos.readPostAll();


    }
 
Example #6
Source File: CubaJavaScriptComponent.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected static GsonBuilder createSharedGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();
    builder.setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            Expose expose = f.getAnnotation(Expose.class);
            return expose != null && !expose.serialize();
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    });

    setDefaultProperties(builder);
    return builder;
}
 
Example #7
Source File: OkApiModule.java    From Forage with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Custom Gson to make Retrofit Gson adapter work with Realm objects
 */
@NonNull
@Provides
@Singleton
public static Gson provideGson(@NonNull ListTypeAdapterFactory jsonArrayTypeAdapterFactory,
                               @NonNull HtmlAdapter htmlAdapter,
                               @NonNull StringCapitalizerAdapter stringCapitalizerAdapter) {

    return new GsonBuilder()
            .setExclusionStrategies(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes f) {
                    return f.getDeclaringClass().equals(RealmObject.class);
                }

                @Override
                public boolean shouldSkipClass(Class<?> clazz) {
                    return false;
                }
            })
            .registerTypeAdapterFactory(jsonArrayTypeAdapterFactory)
            .registerTypeAdapter(String.class, htmlAdapter)
            .registerTypeAdapter(String.class, stringCapitalizerAdapter)
            .create();
}
 
Example #8
Source File: WGsonConvert.java    From wES with MIT License 6 votes vote down vote up
/**
 * 构建通用GsonBuilder, 封装初始化工作
 *
 * @return
 */
public static GsonBuilder getGsonBuilder(boolean prettyPrinting) {
	GsonBuilder gb = new GsonBuilder();
	gb.setDateFormat("yyyy-MM-dd HH:mm:ss:mss");
	gb.setExclusionStrategies(new ExclusionStrategy() {
		@Override
		public boolean shouldSkipField(FieldAttributes f) {
			return f.getAnnotation(WJsonExclued.class) != null;
		}

		@Override
		public boolean shouldSkipClass(Class<?> clazz) {
			return clazz.getAnnotation(WJsonExclued.class) != null;
		}
	});
	if (prettyPrinting)
		gb.setPrettyPrinting();
	return gb;
}
 
Example #9
Source File: WJsonUtils.java    From wES with MIT License 6 votes vote down vote up
/**
 * 构建通用GsonBuilder, 封装初始化工作
 *
 * @return
 */
public static GsonBuilder getGsonBuilder(boolean prettyPrinting) {
	GsonBuilder gb = new GsonBuilder();
	gb.setDateFormat("yyyy-MM-dd HH:mm:ss:mss");
	gb.setExclusionStrategies(new ExclusionStrategy() {
		@Override
		public boolean shouldSkipField(FieldAttributes f) {
			return f.getAnnotation(WJsonExclued.class) != null;
		}

		@Override
		public boolean shouldSkipClass(Class<?> clazz) {
			return clazz.getAnnotation(WJsonExclued.class) != null;
		}
	});
	if (prettyPrinting)
		gb.setPrettyPrinting();
	return gb;
}
 
Example #10
Source File: GsonProvider.java    From mvvm-template with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Make gson which {@link DateDeserializer} and compatible with {@link RealmObject}
 * @return {@link Gson} object
 */
public static Gson makeGsonForRealm() {
    return makeDefaultGsonBuilder()
            .setExclusionStrategies(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes f) {
                    return f.getDeclaringClass().equals(RealmObject.class);
                }

                @Override
                public boolean shouldSkipClass(Class<?> clazz) {
                    return false;
                }
            })
            .create();
}
 
Example #11
Source File: JobDescriptor.java    From xml-job-to-job-dsl-plugin with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String toString() {
    GsonBuilder builder = new GsonBuilder();
    builder.setExclusionStrategies(new ExclusionStrategy() {

        @Override
        public boolean shouldSkipField(FieldAttributes fieldAttributes) {
            return fieldAttributes.getName().equals("parent");
        }

        @Override
        public boolean shouldSkipClass(Class<?> aClass) {
            return false;
        }
    });
    builder.setPrettyPrinting();
    return builder.create().toJson(this).replaceAll(Pattern.quote("\\r"), Matcher.quoteReplacement(""));
}
 
Example #12
Source File: PropertyDescriptor.java    From xml-job-to-job-dsl-plugin with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String toString() {
    GsonBuilder builder = new GsonBuilder();
    builder.setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes fieldAttributes) {
            return fieldAttributes.getName().equals("parent");
        }

        @Override
        public boolean shouldSkipClass(Class<?> aClass) {
            return false;
        }
    });
    return builder.create().toJson(this).replaceAll(Pattern.quote("\\r"), Matcher.quoteReplacement(""));
}
 
Example #13
Source File: Excluder.java    From letv with Apache License 2.0 6 votes vote down vote up
public boolean excludeClass(Class<?> clazz, boolean serialize) {
    if (this.version != IGNORE_VERSIONS && !isValidVersion((Since) clazz.getAnnotation(Since.class), (Until) clazz.getAnnotation(Until.class))) {
        return true;
    }
    if (!this.serializeInnerClasses && isInnerClass(clazz)) {
        return true;
    }
    if (isAnonymousOrLocal(clazz)) {
        return true;
    }
    for (ExclusionStrategy exclusionStrategy : serialize ? this.serializationStrategies : this.deserializationStrategies) {
        if (exclusionStrategy.shouldSkipClass(clazz)) {
            return true;
        }
    }
    return false;
}
 
Example #14
Source File: Excluder.java    From framework with GNU Affero General Public License v3.0 6 votes vote down vote up
public boolean excludeClass(Class<?> clazz, boolean serialize) {
  if (version != Excluder.IGNORE_VERSIONS
      && !isValidVersion(clazz.getAnnotation(Since.class), clazz.getAnnotation(Until.class))) {
    return true;
  }

  if (!serializeInnerClasses && isInnerClass(clazz)) {
    return true;
  }

  if (isAnonymousOrLocal(clazz)) {
    return true;
  }

  List<ExclusionStrategy> list = serialize ? serializationStrategies : deserializationStrategies;
  for (ExclusionStrategy exclusionStrategy : list) {
    if (exclusionStrategy.shouldSkipClass(clazz)) {
      return true;
    }
  }

  return false;
}
 
Example #15
Source File: WJsonUtils.java    From DAFramework with MIT License 6 votes vote down vote up
/**
 * 构建通用GsonBuilder, 封装初始化工作
 *
 * @return
 */
public static GsonBuilder getGsonBuilder(boolean prettyPrinting) {
	GsonBuilder gb = new GsonBuilder();
	gb.setDateFormat("yyyy-MM-dd HH:mm:ss:mss");
	gb.setExclusionStrategies(new ExclusionStrategy() {
		@Override
		public boolean shouldSkipField(FieldAttributes f) {
			return f.getAnnotation(WJsonExclued.class) != null;
		}

		@Override
		public boolean shouldSkipClass(Class<?> clazz) {
			return clazz.getAnnotation(WJsonExclued.class) != null;
		}
	});
	if (prettyPrinting)
		gb.setPrettyPrinting();
	return gb;
}
 
Example #16
Source File: WebApi.java    From lancoder with GNU General Public License v3.0 6 votes vote down vote up
public WebApi(Master master, WebApiListener eventListener) {
	this.master = master;
	this.eventListener = eventListener;
	WebApi.gson = new GsonBuilder().registerTypeAdapter(CodecEnum.class, new CodecTypeAdapter<>())
			.setExclusionStrategies(new ExclusionStrategy() {
				@Override
				public boolean shouldSkipField(FieldAttributes f) {
					return f.getAnnotation(NoWebUI.class) != null;
				}

				@Override
				public boolean shouldSkipClass(Class<?> clazz) {
					return false;
				}
			}).serializeSpecialFloatingPointValues().create();
}
 
Example #17
Source File: Excluder.java    From gson with Apache License 2.0 5 votes vote down vote up
public Excluder withExclusionStrategy(ExclusionStrategy exclusionStrategy,
    boolean serialization, boolean deserialization) {
  Excluder result = clone();
  if (serialization) {
    result.serializationStrategies = new ArrayList<ExclusionStrategy>(serializationStrategies);
    result.serializationStrategies.add(exclusionStrategy);
  }
  if (deserialization) {
    result.deserializationStrategies
        = new ArrayList<ExclusionStrategy>(deserializationStrategies);
    result.deserializationStrategies.add(exclusionStrategy);
  }
  return result;
}
 
Example #18
Source File: PipelineService.java    From gocd with Apache License 2.0 5 votes vote down vote up
private ExclusionStrategy getGsonExclusionStrategy() {
    return new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getName().equals("materialConfig") || f.getName().equals("parents") || f.getName().equals("children");
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    };
}
 
Example #19
Source File: NGConfiguration.java    From AngularBeans with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static ExclusionStrategy[] getGsonExclusionStrategy() {
	try{
		String exclusionStrategyName = NGConfiguration.getProperty(GSON_EXCLUSION_STRATEGY);
		
		if(exclusionStrategyName != null && exclusionStrategyName.length() > 0){
			return new ExclusionStrategy[]{(ExclusionStrategy) Class.forName(exclusionStrategyName).newInstance()};
		}
	} catch (Exception e){
		Logger.getLogger(NGConfiguration.class.getName()).severe(e.toString());
	}

	// Needs to return empty array explicitly instead of null because of GsonBuilder's setExclusionStrategies() varargs
	return new ExclusionStrategy[]{};
}
 
Example #20
Source File: Excluder.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
public boolean excludeClass(Class class1, boolean flag)
{
    if (b != -1D && !a((Since)class1.getAnnotation(com/google/gson/annotations/Since), (Until)class1.getAnnotation(com/google/gson/annotations/Until)))
    {
        return true;
    }
    if (!d && b(class1))
    {
        return true;
    }
    if (a(class1))
    {
        return true;
    }
    List list;
    Iterator iterator;
    if (flag)
    {
        list = f;
    } else
    {
        list = g;
    }
    for (iterator = list.iterator(); iterator.hasNext();)
    {
        if (((ExclusionStrategy)iterator.next()).shouldSkipClass(class1))
        {
            return true;
        }
    }

    return false;
}
 
Example #21
Source File: Excluder.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
public Excluder withExclusionStrategy(ExclusionStrategy exclusionstrategy, boolean flag, boolean flag1)
{
    Excluder excluder = clone();
    if (flag)
    {
        excluder.f = new ArrayList(f);
        excluder.f.add(exclusionstrategy);
    }
    if (flag1)
    {
        excluder.g = new ArrayList(g);
        excluder.g.add(exclusionstrategy);
    }
    return excluder;
}
 
Example #22
Source File: Excluder.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
public Excluder withExclusionStrategy(ExclusionStrategy exclusionStrategy,
    boolean serialization, boolean deserialization) {
  Excluder result = clone();
  if (serialization) {
    result.serializationStrategies = new ArrayList<ExclusionStrategy>(serializationStrategies);
    result.serializationStrategies.add(exclusionStrategy);
  }
  if (deserialization) {
    result.deserializationStrategies
        = new ArrayList<ExclusionStrategy>(deserializationStrategies);
    result.deserializationStrategies.add(exclusionStrategy);
  }
  return result;
}
 
Example #23
Source File: AppModule.java    From jianshi with Apache License 2.0 5 votes vote down vote up
@Provides
ExclusionStrategy provideExclusionStrategy() {
  return new ExclusionStrategy() {
    @Override
    public boolean shouldSkipField(FieldAttributes f) {
      return false;
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
      return clazz.equals(ModelAdapter.class);
    }
  };
}
 
Example #24
Source File: SerializationWithExclusionsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenExclusionStrategyByClassesAndFields_whenSerializing_thenFollowStrategy() {
    MyClass source = new MyClass(1L, "foo", "bar", new MySubClass(42L, "the answer", "Verbose field which we don't want to be serialized"));
    ExclusionStrategy strategy = new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes field) {
            if (field.getDeclaringClass() == MyClass.class && field.getName()
                .equals("other"))
                return true;
            if (field.getDeclaringClass() == MySubClass.class && field.getName()
                .equals("otherVerboseInfo"))
                return true;
            return false;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    };

    Gson gson = new GsonBuilder().addSerializationExclusionStrategy(strategy)
        .create();
    String jsonString = gson.toJson(source);

    assertEquals(expectedResult, jsonString);
}
 
Example #25
Source File: GsonHelper.java    From highchart-java-api with Apache License 2.0 5 votes vote down vote up
private GsonHelper() {
    gsonBuilder = new GsonBuilder()
    .registerTypeAdapter(
            DateTimeLabelFormats.class, 
            new DateTimeLabelFormatsSerializer()) //
    .registerTypeAdapter(
            Style.class, 
            new StyleSerializer())//
    .registerTypeAdapter(
            NullableDouble.class, 
            new NullableDoubleSerializer())
    .serializeSpecialFloatingPointValues()
    .setDateFormat(GsonHelper.DATE_FORMAT)//
    .setExclusionStrategies(new ExclusionStrategy() {

        @Override
        public boolean shouldSkipClass(Class<?> arg0) {
            return false;
        }

        @Override
        public boolean shouldSkipField(FieldAttributes attributes) {
            return attributes.getName().equals(GsonHelper.USER_OBJECT);
        }

    });
}
 
Example #26
Source File: Excluder.java    From gson with Apache License 2.0 5 votes vote down vote up
private boolean excludeClassInStrategy(Class<?> clazz, boolean serialize) {
    List<ExclusionStrategy> list = serialize ? serializationStrategies : deserializationStrategies;
    for (ExclusionStrategy exclusionStrategy : list) {
        if (exclusionStrategy.shouldSkipClass(clazz)) {
            return true;
        }
    }
    return false;
}
 
Example #27
Source File: ExclusionStrategyFunctionalTest.java    From gson with Apache License 2.0 5 votes vote down vote up
private static Gson createGson(ExclusionStrategy exclusionStrategy, boolean serialization) {
  GsonBuilder gsonBuilder = new GsonBuilder();
  if (serialization) {
    gsonBuilder.addSerializationExclusionStrategy(exclusionStrategy);
  } else {
    gsonBuilder.addDeserializationExclusionStrategy(exclusionStrategy);
  }
  return gsonBuilder
      .serializeNulls()
      .create();
}
 
Example #28
Source File: UserService.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Facility method to easily provide user content with resolved lazy fields
 * to be able to serialize. The method takes care of the possible cycles
 * such as "users->pref->filescanners->collections->users" ...
 * It also removes possible huge product list from collections.
 *
 * @param u the user to resolve.
 * @return the resolved user.
 */
@Transactional (readOnly=true, propagation=Propagation.REQUIRED)
@Cacheable (value = "json_user", key = "#u")
public User resolveUser (User u)
{
   u = userDao.read(u.getUUID());
   Gson gson = new GsonBuilder().setExclusionStrategies (
      new ExclusionStrategy()
      {
         public boolean shouldSkipClass(Class<?> clazz)
         {
            // Avoid huge number of products in collection
            return clazz==Product.class;
         }
         /**
          * Custom field exclusion goes here
          */
         public boolean shouldSkipField(FieldAttributes f)
         {
            // Avoid cycles caused by collection tree and user/auth users...
            return f.getName().equals("authorizedUsers") ||
                   f.getName().equals("parent") ||
                   f.getName().equals("subCollections");

         }
      }).serializeNulls().create();
   String users_string = gson.toJson(u);
   return gson.fromJson(users_string, User.class);
}
 
Example #29
Source File: GsonRealmBuilder.java    From batteryhub with Apache License 2.0 5 votes vote down vote up
private static GsonBuilder getBuilder() {
    return new GsonBuilder()
            .setExclusionStrategies(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes f) {
                    return f.getDeclaringClass().equals(RealmObject.class);
                }

                @Override
                public boolean shouldSkipClass(Class<?> clazz) {
                    return false;
                }
            });
}
 
Example #30
Source File: ApiClient.java    From ApiClient with Apache License 2.0 5 votes vote down vote up
/**
 * Get the api singleton from the api interface
 *
 * @return api
 */
@Override
public Api getApi() {
    if (mApi == null) {
        mApi = new Retrofit.Builder()
                .client(new OkHttpClient.Builder()
                        .addInterceptor(API_KEY_INTERCEPTOR)
                        .build())
                .baseUrl(mApiBaseUrl)
                .addConverterFactory(GsonConverterFactory.create(getGsonBuilder(new GsonBuilder())
                        .setExclusionStrategies(new ExclusionStrategy() {
                            @Override
                            public boolean shouldSkipField(FieldAttributes f) {
                                return f.getDeclaringClass().equals(RealmObject.class);
                            }

                            @Override
                            public boolean shouldSkipClass(Class<?> clazz) {
                                return false;
                            }
                        })
                        .create()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build()
                .create(mClazz);
    }
    return mApi;
}