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 Project: mycore   Author: MyCoRe-Org   File: MCRPIService.java    License: 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 Project: xml-job-to-job-dsl-plugin   Author: jenkinsci   File: JobDescriptor.java    License: 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 #3
Source Project: xml-job-to-job-dsl-plugin   Author: jenkinsci   File: PropertyDescriptor.java    License: 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 #4
Source Project: letv   Author: JackChan1999   File: Excluder.java    License: 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 #5
Source Project: DAFramework   Author: DataAgg   File: WJsonUtils.java    License: 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 #6
Source Project: mvvm-template   Author: duyp   File: GsonProvider.java    License: 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 #7
Source Project: wES   Author: DataSays   File: WJsonUtils.java    License: 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 #8
Source Project: wES   Author: DataSays   File: WGsonConvert.java    License: 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 Project: Forage   Author: Plastix   File: OkApiModule.java    License: 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 #10
Source Project: cuba   Author: cuba-platform   File: CubaJavaScriptComponent.java    License: 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 #11
Source Project: ExamplesAndroid   Author: David-Hackro   File: Servicios.java    License: 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 #12
Source Project: framework   Author: Odoo-mobile   File: Excluder.java    License: 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 #13
Source Project: lancoder   Author: jdupl   File: WebApi.java    License: 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 #14
Source Project: tutorials   Author: eugenp   File: SerializationWithExclusionsUnitTest.java    License: 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 #15
Source Project: tutorials   Author: eugenp   File: SerializationWithExclusionsUnitTest.java    License: 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 #16
Source Project: pagarme-java   Author: pagarme   File: JSONUtils.java    License: 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 #17
Source Project: Collection-Android   Author: usernameyangyan   File: GsonUtils.java    License: MIT License 5 votes vote down vote up
private static Gson getGsonExpose() {
    if (gsonExpose == null) {
        ExclusionStrategy excludeStrategy = new SetterExclusionStrategy(Config.EXPOSEPARAM);
        gsonExpose = new GsonBuilder().setExclusionStrategies(excludeStrategy)
                .create();
    }
    return gsonExpose;
}
 
Example #18
Source Project: BadIntent   Author: mateuszk87   File: SerializationUtils.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@NonNull
public static Gson createGson() {
    return new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes f) {
                return f.getAnnotation(NotSerializable.class) != null;
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
                return false;
            }
        }).create();
}
 
Example #19
Source Project: github-autostatus-plugin   Author: jenkinsci   File: HttpNotifier.java    License: MIT License 5 votes vote down vote up
public HttpNotifier(HttpNotifierConfig config) {
    if (null == config || Strings.isNullOrEmpty(config.getHttpEndpoint())) {
        return;
    }
    this.repoOwner = config.getRepoOwner();
    this.repoName = config.getRepoName();
    this.branchName = config.getBranchName();
    this.config = config;
    this.stageMap = new HashMap<>();
    UsernamePasswordCredentials credentials = config.getCredentials();
    if (credentials != null) {
        String username = credentials.getUsername();
        String password = credentials.getPassword().getPlainText();

        authorization = Base64.getEncoder().encodeToString(
                String.format("%s:%s", username, password).getBytes(StandardCharsets.UTF_8));
    }
    gson = new GsonBuilder()
            .addSerializationExclusionStrategy(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes f) {
                    return f.getAnnotation(SkipSerialisation.class) != null;
                }

                @Override
                public boolean shouldSkipClass(Class<?> clazz) {
                    return false;
                }
            })
            .create();
}
 
Example #20
Source Project: letv   Author: JackChan1999   File: Excluder.java    License: 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(this.serializationStrategies);
        result.serializationStrategies.add(exclusionStrategy);
    }
    if (deserialization) {
        result.deserializationStrategies = new ArrayList(this.deserializationStrategies);
        result.deserializationStrategies.add(exclusionStrategy);
    }
    return result;
}
 
Example #21
Source Project: letv   Author: JackChan1999   File: Excluder.java    License: Apache License 2.0 5 votes vote down vote up
public boolean excludeField(Field field, boolean serialize) {
    if ((this.modifiers & field.getModifiers()) != 0) {
        return true;
    }
    if (this.version != IGNORE_VERSIONS && !isValidVersion((Since) field.getAnnotation(Since.class), (Until) field.getAnnotation(Until.class))) {
        return true;
    }
    if (field.isSynthetic()) {
        return true;
    }
    if (this.requireExpose) {
        Expose annotation = (Expose) field.getAnnotation(Expose.class);
        if (annotation == null || (serialize ? !annotation.serialize() : !annotation.deserialize())) {
            return true;
        }
    }
    if (!this.serializeInnerClasses && isInnerClass(field.getType())) {
        return true;
    }
    if (isAnonymousOrLocal(field.getType())) {
        return true;
    }
    List<ExclusionStrategy> list = serialize ? this.serializationStrategies : this.deserializationStrategies;
    if (!list.isEmpty()) {
        FieldAttributes fieldAttributes = new FieldAttributes(field);
        for (ExclusionStrategy exclusionStrategy : list) {
            if (exclusionStrategy.shouldSkipField(fieldAttributes)) {
                return true;
            }
        }
    }
    return false;
}
 
Example #22
Source Project: java   Author: json-iterator   File: GsonCompatibilityMode.java    License: MIT License 5 votes vote down vote up
@Override
public Config.Builder copy() {
    Builder copied = (Builder) super.copy();
    copied.excludeFieldsWithoutExposeAnnotation = excludeFieldsWithoutExposeAnnotation;
    copied.disableHtmlEscaping = disableHtmlEscaping;
    copied.dateFormat = dateFormat;
    copied.fieldNamingStrategy = fieldNamingStrategy;
    copied.version = version;
    copied.serializationExclusionStrategies = new HashSet<ExclusionStrategy>(serializationExclusionStrategies);
    copied.deserializationExclusionStrategies = new HashSet<ExclusionStrategy>(deserializationExclusionStrategies);
    return copied;
}
 
Example #23
Source Project: talk-android   Author: jianliaoim   File: GsonProvider.java    License: MIT License 5 votes vote down vote up
public Builder addDeserializationExclusionStrategy(final String key) {
    builder.addDeserializationExclusionStrategy(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getName().equals(key);
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    });
    return this;
}
 
Example #24
Source Project: ApiClient   Author: FabianTerhorst   File: ApiClient.java    License: 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;
}
 
Example #25
Source Project: batteryhub   Author: greenhub-project   File: GsonRealmBuilder.java    License: 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 #26
Source Project: DataHubSystem   Author: SentinelDataHub   File: UserService.java    License: 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 #27
Source Project: AngularBeans   Author: bessemHmidi   File: NGConfiguration.java    License: 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 #28
Source Project: MiBandDecompiled   Author: vishnudevk   File: Excluder.java    License: 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 #29
Source Project: MiBandDecompiled   Author: vishnudevk   File: Excluder.java    License: 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 #30
Source Project: gson   Author: google   File: Excluder.java    License: 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;
}