Example usage for com.google.gson ExclusionStrategy ExclusionStrategy

List of usage examples for com.google.gson ExclusionStrategy ExclusionStrategy

Introduction

In this page you can find the example usage for com.google.gson ExclusionStrategy ExclusionStrategy.

Prototype

ExclusionStrategy

Source Link

Usage

From source file:com.example.sampledemo.request.GsonRequest.java

License:Apache License

public GsonRequest(int method, String url, Type type, String requestBody, Listener<T> listener,
        ErrorListener errorListener) {
    super(method, url, errorListener);
    mJavaClass = type;/*from   www.j av  a  2 s  .com*/
    mListener = listener;
    mRequestBody = requestBody;
    mGson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return false;//f.getDeclaringClass().equals(RealmObject.class);
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    }).create();
}

From source file:com.google.api.ads.adwords.keywordoptimizer.api.JsonUtil.java

License:Open Source License

/**
 * Initializes Gson to convert objects to and from JSON. This method customizes a "plain" Gson by
 * adding appropriate exclusions strategies / adapters as needed in this project for a "pretty"
 * output. /*  w w  w  .  j a  v  a 2s. com*/
 */
private static Gson initGson(boolean prettyPrint) {
    GsonBuilder builder = new GsonBuilder();

    // Exclude superclasses.
    ExclusionStrategy superclassExclusionStrategy = new SuperclassExclusionStrategy();
    builder.addDeserializationExclusionStrategy(superclassExclusionStrategy);
    builder.addSerializationExclusionStrategy(superclassExclusionStrategy);

    // Exclude underscore fields in client lib objects.
    ExclusionStrategy underscoreExclusionStrategy = new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes field) {
            if (field.getName().startsWith("_")) {
                return true;
            }

            return false;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    };
    builder.addDeserializationExclusionStrategy(underscoreExclusionStrategy);
    builder.addSerializationExclusionStrategy(underscoreExclusionStrategy);

    // Render KeywordCollection as an array of KeywordInfos.
    builder.registerTypeAdapter(KeywordCollection.class, new JsonSerializer<KeywordCollection>() {
        @Override
        public JsonElement serialize(KeywordCollection src, java.lang.reflect.Type typeOfSrc,
                JsonSerializationContext context) {
            JsonArray out = new JsonArray();
            for (KeywordInfo info : src.getListSortedByScore()) {
                out.add(context.serialize(info));
            }
            return out;
        }
    });
    // Render Money as a primitive.
    builder.registerTypeAdapter(Money.class, new JsonSerializer<Money>() {
        @Override
        public JsonElement serialize(Money src, java.lang.reflect.Type typeOfSrc,
                JsonSerializationContext context) {
            JsonElement out = new JsonPrimitive(src.getMicroAmount() / 1000000);
            return out;
        }
    });
    // Render Keyword in a simple way.
    builder.registerTypeAdapter(Keyword.class, new JsonSerializer<Keyword>() {
        @Override
        public JsonElement serialize(Keyword src, java.lang.reflect.Type typeOfSrc,
                JsonSerializationContext context) {
            JsonObject out = new JsonObject();
            out.addProperty("text", src.getText());
            out.addProperty("matchtype", src.getMatchType().toString());
            return out;
        }
    });
    // Render Throwable in a simple way (for all subclasses).
    builder.registerTypeHierarchyAdapter(Throwable.class, new JsonSerializer<Throwable>() {
        @Override
        public JsonElement serialize(Throwable src, java.lang.reflect.Type typeOfSrc,
                JsonSerializationContext context) {
            JsonObject out = new JsonObject();
            out.addProperty("message", src.getMessage());
            out.addProperty("type", src.getClass().getName());

            JsonArray stack = new JsonArray();
            for (StackTraceElement stackTraceElement : src.getStackTrace()) {
                JsonObject stackElem = new JsonObject();
                stackElem.addProperty("file", stackTraceElement.getFileName());
                stackElem.addProperty("line", stackTraceElement.getLineNumber());
                stackElem.addProperty("method", stackTraceElement.getMethodName());
                stackElem.addProperty("class", stackTraceElement.getClassName());
                stack.add(stackElem);
            }
            out.add("stack", stack);

            if (src.getCause() != null) {
                out.add("cause", context.serialize(src.getCause()));
            }
            return out;
        }
    });

    if (prettyPrint) {
        builder.setPrettyPrinting();
    }

    return builder.create();
}

From source file:com.google.belay.server.GsonUtil.java

License:Open Source License

public static GsonBuilder getGsonBuilder() {
    GsonBuilder gb = new GsonBuilder();
    gb.registerTypeAdapter(Capability.class, new CapabilityAdapter());
    gb.setExclusionStrategies(new ExclusionStrategy() {

        @Override/*www . j av  a 2s .  c  o  m*/
        public boolean shouldSkipField(FieldAttributes attrs) {
            return attrs.getAnnotation(HideFromClient.class) != null;
        }

        @Override
        public boolean shouldSkipClass(Class<?> cls) {
            return false;
        }
    });

    return gb;
}

From source file:com.google.gerrit.httpd.restapi.RestApiServlet.java

License:Apache License

private static void enablePartialGetFields(GsonBuilder gb, Multimap<String, String> config) {
    final Set<String> want = Sets.newHashSet();
    for (String p : config.get("fields")) {
        Iterables.addAll(want, OptionUtil.splitOptionValue(p));
    }/*from  w  w  w .j a  v  a  2  s.c om*/
    if (!want.isEmpty()) {
        gb.addSerializationExclusionStrategy(new ExclusionStrategy() {
            private final Map<String, String> names = Maps.newHashMap();

            @Override
            public boolean shouldSkipField(FieldAttributes field) {
                String name = names.get(field.getName());
                if (name == null) {
                    // Names are supplied by Gson in terms of Java source.
                    // Translate and cache the JSON lower_case_style used.
                    try {
                        name = FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES.translateName(//
                                field.getDeclaringClass().getDeclaredField(field.getName()));
                        names.put(field.getName(), name);
                    } catch (SecurityException e) {
                        return true;
                    } catch (NoSuchFieldException e) {
                        return true;
                    }
                }
                return !want.contains(name);
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
                return false;
            }
        });
    }
}

From source file:com.hmatalonga.greenhub.util.GsonRealmBuilder.java

License:Apache License

private static GsonBuilder getBuilder() {
    return new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        @Override//from  w ww  .  ja va2 s. co m
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getDeclaringClass().equals(RealmObject.class);
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    });
}

From source file:com.jd.survey.service.util.JsonHelperService.java

License:Open Source License

public String serializeSurveyDefinition(SurveyDefinition surveyDefinition) {
    try {//w w w . j a  v a2s  .c o m
        GsonBuilder gsonBuilder = new GsonBuilder();
        //set up the fields to skip in the serialization
        gsonBuilder = gsonBuilder.setExclusionStrategies(new ExclusionStrategy() {
            public boolean shouldSkipClass(Class<?> clazz) {
                return false;
            }

            @Override
            public boolean shouldSkipField(FieldAttributes f) {
                boolean skip = (f.getDeclaringClass() == SurveyDefinition.class && f.getName().equals("id"))
                        || (f.getDeclaringClass() == SurveyDefinition.class && f.getName().equals("version"))
                        || (f.getDeclaringClass() == SurveyDefinition.class && f.getName().equals("department"))
                        || (f.getDeclaringClass() == SurveyDefinition.class && f.getName().equals("users"))
                        || (f.getDeclaringClass() == SurveyDefinitionPage.class && f.getName().equals("id"))
                        || (f.getDeclaringClass() == SurveyDefinitionPage.class
                                && f.getName().equals("surveyDefinition"))
                        || (f.getDeclaringClass() == Question.class && f.getName().equals("id"))
                        || (f.getDeclaringClass() == Question.class && f.getName().equals("version"))
                        || (f.getDeclaringClass() == Question.class && f.getName().equals("page"))
                        || (f.getDeclaringClass() == Question.class && f.getName().equals("optionsList"))
                        || (f.getDeclaringClass() == Question.class && f.getName().equals("rowLabelsList"))
                        || (f.getDeclaringClass() == Question.class && f.getName().equals("columnLabelsList"))
                        || (f.getDeclaringClass() == QuestionOption.class && f.getName().equals("id"))
                        || (f.getDeclaringClass() == QuestionOption.class && f.getName().equals("version"))
                        || (f.getDeclaringClass() == QuestionOption.class && f.getName().equals("question"))
                        || (f.getDeclaringClass() == QuestionRowLabel.class && f.getName().equals("id"))
                        || (f.getDeclaringClass() == QuestionRowLabel.class && f.getName().equals("version"))
                        || (f.getDeclaringClass() == QuestionRowLabel.class && f.getName().equals("question"))
                        || (f.getDeclaringClass() == QuestionColumnLabel.class && f.getName().equals("id"))
                        || (f.getDeclaringClass() == QuestionColumnLabel.class && f.getName().equals("version"))
                        || (f.getDeclaringClass() == QuestionColumnLabel.class
                                && f.getName().equals("question"));
                return skip;
            }

        });

        //de-proxy the object
        gsonBuilder.registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxySerializer());
        Hibernate.initialize(surveyDefinition);
        if (surveyDefinition instanceof HibernateProxy) {
            surveyDefinition = (SurveyDefinition) ((HibernateProxy) surveyDefinition)
                    .getHibernateLazyInitializer().getImplementation();
        }
        Gson gson = gsonBuilder.serializeNulls().create();
        return gson.toJson(surveyDefinition);

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }

}

From source file:com.nouveauxterritoires.eterritoires.identityserver.openid.connect.view.TaxeUserInfoViewForAdmins.java

License:Apache License

/**
 * @return/*from  ww  w. ja  va  2s .  c o m*/
 */
@Override
protected ExclusionStrategy getExclusionStrategy() {
    return new ExclusionStrategy() {

        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            if (blacklistedFields.contains(f.getName())) {
                return true;
            } else {
                return false;
            }
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            // skip the JPA binding wrapper
            if (clazz.equals(BeanPropertyBindingResult.class)) {
                return true;
            }
            return false;
        }

    };
}

From source file:com.nouveauxterritoires.eterritoires.identityserver.openid.connect.view.TaxeUserInfoViewForUsers.java

License:Apache License

@Override
protected ExclusionStrategy getExclusionStrategy() {
    return new ExclusionStrategy() {

        @Override//  w  ww . j  a  v a2 s.  c  om
        public boolean shouldSkipField(FieldAttributes f) {
            // whitelist the handful of fields that are good
            if (whitelistedFields.contains(f.getName())) {
                return false;
            } else {
                return true;
            }
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            // skip the JPA binding wrapper
            if (clazz.equals(BeanPropertyBindingResult.class)) {
                return true;
            }
            return false;
        }

    };
}

From source file:com.shazam.shazamcrest.GsonProvider.java

License:Apache License

/**
 * Returns a {@link Gson} instance containing {@link ExclusionStrategy} based on the object types to ignore during
 * serialisation/deserialisation./*from  w ww .j av a 2 s  .c om*/
 * 
 * @param typesToIgnore the object types to exclude from serialisation/deserialisation.
 * @return an instance of {@link Gson}
 */
public static Gson gson(final List<Class<?>> typesToIgnore) {
    if (typesToIgnore.size() == 0) {
        return GsonProvider.GSON;
    } else {
        return new GsonBuilder().setPrettyPrinting().enableComplexMapKeySerialization()
                .setExclusionStrategies(new ExclusionStrategy() {
                    @Override
                    public boolean shouldSkipField(FieldAttributes f) {
                        return false;
                    }

                    @Override
                    public boolean shouldSkipClass(Class<?> clazz) {
                        return (typesToIgnore.contains(clazz));
                    }

                }).create();
    }
}

From source file:com.shazam.shazamcrest.matcher.GsonProvider.java

License:Apache License

private static void registerExclusionStrategies(GsonBuilder gsonBuilder, final List<Class<?>> typesToIgnore,
        final List<Matcher<String>> fieldsToIgnore) {
    if (typesToIgnore.isEmpty() && fieldsToIgnore.isEmpty()) {
        return;//from  www. j  av a  2s .com
    }

    gsonBuilder.setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            for (Matcher<String> p : fieldsToIgnore) {
                if (p.matches(f.getName())) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return (typesToIgnore.contains(clazz));
        }
    });
}