com.google.gson.FieldAttributes Java Examples

The following examples show how to use com.google.gson.FieldAttributes. 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: 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 #3
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 #4
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 #5
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 #6
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 #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: ApiResponseGsonHelper.java    From cosmic with 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 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 #10
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 #11
Source File: Exclusions.java    From vraptor4 with 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
Source File: HeapAllocStackTraceExclStrat.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 File: ApiResponseGsonHelper.java    From cloudstack with 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 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 #15
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 #16
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 #17
Source File: SetterExclusionStrategy.java    From Collection-Android with 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
Source File: ZemberekExclusionStrategy.java    From zemberek-nlp-server with GNU General Public License v3.0 5 votes vote down vote up
@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
Source File: SerializationUtils.java    From BadIntent with 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 #20
Source File: HttpNotifier.java    From github-autostatus-plugin with 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 File: Excluder.java    From letv with 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 File: DuplicateFieldExclusionStrategy.java    From opentest with 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
Source File: GsonExclusionStrategy.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public boolean shouldSkipField(FieldAttributes f) {
	if (fieldName != null) {
		return (f.getDeclaringClass().equals(typeToSkip)
				&& f.getName().equals(fieldName));
	}
	return false;
}
 
Example #24
Source File: AnnotatedStrategy.java    From devicehive-java-server with 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 File: GsonProvider.java    From talk-android with 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 File: SuperclassExclusionStrategy.java    From cosmic with 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 File: ApiResponseGsonHelper.java    From cosmic with 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 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;
}
 
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: 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);
}