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: 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 #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: 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: 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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
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 #25
Source File: ApiResponseGsonHelper.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public boolean shouldSkipField(FieldAttributes f) {
    Param param = f.getAnnotation(Param.class);
    boolean skip = (param != null && param.isSensitive());
    if (!skip) {
        skip = super.shouldSkipField(f);
    }
    return skip;
}
 
Example #26
Source File: EmptyFieldExclusionStrategy.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Override
public boolean shouldSkipField(FieldAttributes fieldAttributes) {
    if (fieldAttributes.getAnnotation(Param.class) != null) {
        return true;
    }
    return false;
}
 
Example #27
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 #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: ResultProcessStatusExclusion.java    From nfscan with MIT License 5 votes vote down vote up
/**
 * @param f the field object that is under test
 * @return true if the field should be ignored; otherwise false
 */
@Override
public boolean shouldSkipField(FieldAttributes f) {
    if (f.getDeclaringClass() == OCRTransaction.class) {
        return !fieldsOcrTransaction.contains(f.getName());
    } else {
        return false;
    }

}
 
Example #30
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);
    }
  };
}