Java Code Examples for com.google.gson.FieldAttributes

The following examples show how to use com.google.gson.FieldAttributes. These examples are extracted from open source projects. 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   Source 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
@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
@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: DAFramework   Source 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 5
Source Project: mvvm-template   Source 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 6
Source Project: wES   Source 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 7
Source Project: Forage   Source 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 8
Source Project: cosmic   Source File: ApiResponseGsonHelper.java    License: Apache License 2.0 6 votes vote down vote up
public boolean shouldSkipField(final FieldAttributes f) {
    final Param param = f.getAnnotation(Param.class);
    if (param != null) {
        final RoleType[] allowedRoles = param.authorized();
        if (allowedRoles.length > 0) {
            boolean permittedParameter = false;
            final Account caller = CallContext.current().getCallingAccount();
            for (final RoleType allowedRole : allowedRoles) {
                if (allowedRole.getValue() == caller.getType()) {
                    permittedParameter = true;
                    break;
                }
            }
            if (!permittedParameter) {
                return true;
            }
        }
    }
    return false;
}
 
Example 9
Source Project: cuba   Source 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 10
Source Project: ExamplesAndroid   Source 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 11
Source Project: vraptor4   Source File: Exclusions.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean shouldSkipField(FieldAttributes f) {
	SkipSerialization annotation = f.getAnnotation(SkipSerialization.class);
	if (annotation != null)
		return true;
	
	String fieldName = f.getName();
	Class<?> definedIn = f.getDeclaringClass();

	for (Entry<String, Class<?>> include : serializee.getIncludes().entries()) {
		if (isCompatiblePath(include, definedIn, fieldName)) {
			return false;
		}
	}
	for (Entry<String, Class<?>> exclude : serializee.getExcludes().entries()) {
		if (isCompatiblePath(exclude, definedIn, fieldName)) {
			return true;
		}
	}
	
	Field field = reflectionProvider.getField(definedIn, fieldName);
	return !serializee.isRecursive() && !shouldSerializeField(field.getType());
}
 
Example 12
/**
 * This API will filter out field "stackTraceId" of HeapAllocSitesBean class
 * so that it doesn't get printed in json string.
 */
@Override
public boolean shouldSkipField(final FieldAttributes fieldAttrib) {

	if (fieldAttrib.getDeclaringClass().equals(
			HeapAllocSitesBean.SiteDescriptor.class)) {
		try {
			if (EXCLUDED_FIELD_LIST.equals(fieldAttrib.getName())) {
				return true;
			}
		} catch (final SecurityException e) {
			LOGGER.error(e.getMessage());
			return false;
		}
	}
	return false;
}
 
Example 13
Source Project: cloudstack   Source File: ApiResponseGsonHelper.java    License: Apache License 2.0 6 votes vote down vote up
public boolean shouldSkipField(FieldAttributes f) {
    Param param = f.getAnnotation(Param.class);
    if (param != null) {
        RoleType[] allowedRoles = param.authorized();
        if (allowedRoles.length > 0) {
            boolean permittedParameter = false;
            Account caller = CallContext.current().getCallingAccount();
            for (RoleType allowedRole : allowedRoles) {
                if (allowedRole.getAccountType() == caller.getType()) {
                    permittedParameter = true;
                    break;
                }
            }
            if (!permittedParameter) {
                return true;
            }
        }
    }
    return false;
}
 
Example 14
Source Project: lancoder   Source 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 15
Source Project: tutorials   Source 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   Source 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   Source File: SetterExclusionStrategy.java    License: MIT License 5 votes vote down vote up
@Override
public boolean shouldSkipField(FieldAttributes f) {
    if (!TextUtils.isEmpty(field)) {
        if (f.getName().equals(field)) {
            /** true 代表此字段要过滤 */
            return true;
        }
    }

    return false;
}
 
Example 18
@Override
public boolean shouldSkipField(FieldAttributes f) {
    if (f.getName().equals("suffixData") || f.getName().equals("specialRootSuffix") || f.getName().equals("referenceItem")) {
        return true;
    }
    return false;
}
 
Example 19
@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 20
Source Project: github-autostatus-plugin   Source 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 21
Source Project: letv   Source 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: opentest   Source File: DuplicateFieldExclusionStrategy.java    License: MIT License 5 votes vote down vote up
@Override
public boolean shouldSkipField(FieldAttributes fieldAttributes) {
    String fieldName = fieldAttributes.getName();
    Class<?> theClass = fieldAttributes.getDeclaringClass();

    return isFieldInSuperclass(theClass, fieldName);
}
 
Example 23
@Override
public boolean shouldSkipField(FieldAttributes f) {
	if (fieldName != null) {
		return (f.getDeclaringClass().equals(typeToSkip)
				&& f.getName().equals(fieldName));
	}
	return false;
}
 
Example 24
Source Project: devicehive-java-server   Source File: AnnotatedStrategy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean shouldSkipField(FieldAttributes f) {
    JsonPolicyDef policyAnnotation = f.getAnnotation(JsonPolicyDef.class);
    if (policyAnnotation == null) {
        // no policy annotation - filed should be skipped
        return true;
    }
    for (JsonPolicyDef.Policy definedPolicy : policyAnnotation.value()) {
        if (definedPolicy == policy) {
            // policy is found - field is to be included
            return false;
        }
    }
    return true;
}
 
Example 25
Source Project: talk-android   Source 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 26
Source Project: cosmic   Source File: SuperclassExclusionStrategy.java    License: Apache License 2.0 5 votes vote down vote up
public boolean shouldSkipField(FieldAttributes fieldAttributes) {
    String fieldName = fieldAttributes.getName();
    Class<?> theClass = fieldAttributes.getDeclaringClass();
    Class<?> superclass = theClass.getSuperclass();

    if (this.inheritanceMap.containsKey(theClass)) {
        if (getField(this.inheritanceMap.get(theClass), fieldName) != null) {
            return true;
        }
    }

    this.inheritanceMap.put(superclass, theClass);
    return false;
}
 
Example 27
Source Project: cosmic   Source File: ApiResponseGsonHelper.java    License: Apache License 2.0 5 votes vote down vote up
public boolean shouldSkipField(final FieldAttributes f) {
    final Param param = f.getAnnotation(Param.class);
    boolean skip = (param != null && param.isSensitive());
    if (!skip) {
        skip = super.shouldSkipField(f);
    }
    return skip;
}
 
Example 28
Source Project: ApiClient   Source 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 29
Source Project: batteryhub   Source 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 30
/**
 * 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);
}