/** * 构建通用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; }
/** * 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(); }
public static void addFlagToObject(MCRBase obj, MCRPI databaseEntry) { String json = new GsonBuilder().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().toJson(databaseEntry); obj.getService().addFlag(PI_FLAG, json); }
/** * 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(); }
@Before public void setUp() { gson = new GsonBuilder() .registerTypeHierarchyAdapter(Object.class, new RequiredFieldDeserializer()) .registerTypeAdapter(LocalDate.class, new MillisecondsLocalDateAdapter()) .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { return fieldAttributes.getAnnotation(GsonExclude.class) != null; } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }) .create(); }
/** * Retrieves an {@link ExclusionStrategy} that excludes {@link GsonExclude} fields and the classes contained in * {@code excludedClasses}. * * @param strategy the type of the strategy to be retrieved * @return the {@link ExclusionStrategy} for the {@code strategy} provided */ public ExclusionStrategy getExclusionStrategy(@Nullable GsonExclude.Strategy strategy) { return new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { return shouldSkipFieldFromSerialization(fieldAttributes) || (fieldAttributes.getAnnotation(GsonExclude.class) != null && (Objects.equals(fieldAttributes.getAnnotation(GsonExclude.class).strategy(), GsonExclude.Strategy.ALL) || Objects.equals(fieldAttributes.getAnnotation(GsonExclude.class).strategy(), strategy))); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }; }
public static Gson getRobolectricGson(GsonBuilder builder) { return builder .setExclusionStrategies( new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return "__robo_data__".equals(f.getName()); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } } ).create(); }
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; }
@Provides @Singleton RestAPI provideRestAPI() { 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(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(okHttpClient()) .build(); return retrofit.create(RestAPI.class); }
public static Gson getGsonInstance(){ 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; } }) .setDateFormat("yyyy-MM-dd'T'HH:mm:ss") .create(); }
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(); }
public boolean shouldSkipField(FieldAttributes f) { if (this.excludeFields == null) { return false; } for (String field : this.excludeFields) { if (field.equals(f.getName())) { return true; } } return false; }
public static Gson build() { GsonBuilder builder = new GsonBuilder(); builder.addSerializationExclusionStrategy(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getAnnotation(GsonTransient.class) != null; } @Override public boolean shouldSkipClass(Class<?> c) { return c.getAnnotation(GsonTransient.class) != null; } }); return builder.create(); }
/** * GSON can parse the data. * Note there is a bug in GSON 2.3.1 that can cause it to StackOverflow when working with RealmObjects. * To work around this, use the ExclusionStrategy below or downgrade to 1.7.1 * See more here: https://code.google.com/p/google-gson/issues/detail?id=440 * * @param b gs builder body * @return the gbuilder */ protected GsonBuilder configBuilder(GsonBuilder b) { b.setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getDeclaringClass().equals(RealmObject.class); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }); return b; }
public static Gson getGson() { synchronized (lock) { if (gson != null) return 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(); return gson; } }
private static Gson getGson() { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss") .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getDeclaringClass().equals(RealmObject.class); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }) .create(); return gson; }
private static Gson getGson() { return new GsonBuilder() .setDateFormat(Config.ISO_FORMAT) // required for realm.io .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getDeclaringClass().equals(RealmObject.class); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }) .create(); }
public void writeToFile() throws IOException { BufferedReader reader = new BufferedReader(new FileReader(this.location)); GsonBuilder builder = new GsonBuilder().setPrettyPrinting().setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.hasModifier(Modifier.PRIVATE); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }); Gson gson = builder.create(); String json = gson.toJson(this); this.location.createNewFile(); FileWriter writer = new FileWriter(this.location); writer.write(json); writer.close(); }
/** * 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; }
@Override public boolean shouldSkipField(FieldAttributes f) { SyncanoField syncanoField = f.getAnnotation(SyncanoField.class); // Don't serialize read only fields (like "id" or "created_at"). // We want only to receive it, not send. // SyncanoFile is handled in SendRequest // SyncanoObject is handled in SyncanoObjectAdapterFactory if (syncanoField == null || (!readOnlyNotImportant && syncanoField.readOnly() && !syncanoField.required()) || f.getDeclaredClass().isAssignableFrom(SyncanoFile.class) || f.getDeclaredClass().isAssignableFrom(SyncanoObject.class)) { return true; } return false; }
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; }
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(); }
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); } }); }
@Override public boolean shouldSkipField(FieldAttributes fa) { Class objectClass = fa.getDeclaringClass(); List<String> whiteList = null; if (objectClass.equals(ProjectFile.class)) { whiteList = FIELD_WHITELIST_PROJECT_FILE; } else if (objectClass.equals(UploadedFile.class)) { whiteList = FIELD_WHITELIST_UPLOADED_FILE; } if (whiteList != null) { return !whiteList.contains(fa.getName()); } return false; }
public boolean shouldSkipField(FieldAttributes f) { String name = f.getName(); return (f.getDeclaringClass() == Location.class && (name.equals("mResults") || name.equals("mDistance") || name.equals("mInitialBearing") || name.equals("mLat1") || name.equals("mLat2") || name.equals("mLon1") || name.equals("mLon2") || name.equals("mLon2") || name.equals("mHasSpeed") || name.equals("mHasAccuracy") || name.equals("mHasAltitude") || name.equals("mHasBearing") || name.equals("mHasSpeed") || name.equals("mElapsedRealtimeNanos") ) ); }
@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()); }
public static Gson build(final List<String> fields, final List<Class<?>> clazes) { GsonBuilder b = new GsonBuilder(); b.addSerializationExclusionStrategy(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { String field = f.getClass().getSimpleName() + "." + f.getName(); return fields == null ? false : !fields.contains(field); } @Override public boolean shouldSkipClass(Class<?> clazz) { return clazes == null ? false : !clazes.contains(clazz.getSimpleName()); } }); return b.create(); }
public static Gson build(final List<String> fields) { GsonBuilder b = new GsonBuilder(); b.addSerializationExclusionStrategy(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { String field = f.getDeclaringClass().getSimpleName() + "." + f.getName(); return fields == null ? false : !fields.contains(field); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }); return b.create(); }
public static GsonBuilder gsonBuilder() { return new GsonBuilder() // Property visibility .serializeNulls() .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { return false; } @Override public boolean shouldSkipClass(Class<?> aClass) { return false; } }) .excludeFieldsWithModifiers(Modifier.PROTECTED) .excludeFieldsWithoutExposeAnnotation() // Property naming and order .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setFieldNamingStrategy((field) -> field.getName().toLowerCase()) // Customised de/serializers // Formats, locals, encoding, binary data .setDateFormat("MM/dd/yyyy") .setPrettyPrinting(); }
@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(); }
/** * 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. * @deprecated Please use securityService.getCurrentUser() instead. */ @Transactional (readOnly=true, propagation=Propagation.REQUIRED) @Deprecated 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); }
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; }
@Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { String fieldName = fieldAttributes.getName(); Class<?> theClass = fieldAttributes.getDeclaringClass(); return isFieldInSuperclass(theClass, fieldName); }
@Override public RouteGroup routes() { return () -> { before("/*", (request, response) -> log.info("endpoint: " + request.pathInfo())); get("/", this::getTutorList, tutors -> { // Return only the required fields in JSON response Gson gson = new GsonBuilder() .addSerializationExclusionStrategy(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { final Expose expose = fieldAttributes.getAnnotation(Expose.class); // Skip "courseRequirements" field in tutor list deserialization return expose == null || !expose.serialize() || (fieldAttributes.getDeclaringClass() == Course.class && fieldAttributes.getName().equals("courseRequirements")); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }) .setPrettyPrinting() .create(); return gson.toJson(tutors); }); get("/:id", this::getTutor, gson::toJson); }; }
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; }
@Provides @Singleton Gson provideGson() { return new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .setLenient() .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getDeclaringClass().equals(RealmObject.class); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }) .registerTypeAdapter(new TypeToken<RealmList<RealmString>>(){}.getType(), new TypeAdapter<RealmList<RealmString>>() { @Override public void write(JsonWriter out, RealmList<RealmString> value) throws IOException { out.beginArray(); for (RealmString string : value) out.value(string.value); out.endArray(); } @Override public RealmList<RealmString> read(JsonReader in) throws IOException { RealmList<RealmString> list = new RealmList<>(); in.beginArray(); while (in.hasNext()) list.add(new RealmString(in.nextString())); in.endArray(); return list; } }) .create(); }
@Override public boolean shouldSkipField(FieldAttributes f) { if (fieldName != null) { return (f.getDeclaringClass().equals(typeToSkip) && f.getName().equals(fieldName)); } return false; }