Example usage for com.google.gson GsonBuilder setExclusionStrategies

List of usage examples for com.google.gson GsonBuilder setExclusionStrategies

Introduction

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

Prototype

public GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies) 

Source Link

Document

Configures Gson to apply a set of exclusion strategies during both serialization and deserialization.

Usage

From source file:ca.oson.json.Oson.java

License:Open Source License

public Gson getGson() {
    if (gson == null) {
        GsonBuilder gsonBuilder = new GsonBuilder();

        switch (getDefaultType()) {
        case ALWAYS:
            gsonBuilder.serializeNulls();
            break;
        case NON_NULL:
            break;
        case NON_EMPTY:
            break;
        case DEFAULT:
            gsonBuilder.serializeNulls();
            break;
        default:/*w w  w. j  a  va  2  s .c  o  m*/
            gsonBuilder.serializeNulls();
            break;
        }

        switch (getFieldNaming()) {
        case FIELD: // original field name: someField_name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
            break;
        case LOWER: // somefield_name -> some_field_name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UPPER: //SOMEFIELD_NAME -> SomeFieldName
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
            break;
        case CAMELCASE: // someFieldName
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
            break;
        case UPPER_CAMELCASE: // SomeFieldName
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
            break;
        case UNDERSCORE_CAMELCASE: // some_Field_Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UNDERSCORE_UPPER_CAMELCASE: // Some_Field_Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UNDERSCORE_LOWER: // some_field_name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UNDERSCORE_UPPER: // SOME_FIELD_NAME
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case SPACE_CAMELCASE: // some Field Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case SPACE_UPPER_CAMELCASE: // Some Field Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case SPACE_LOWER: // some field name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case SPACE_UPPER: // SOME FIELD NAME
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case DASH_CAMELCASE: // some-Field-Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        case DASH_UPPER_CAMELCASE: // Some-Field-Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        case DASH_LOWER: // some-field-name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        case DASH_UPPER: // SOME-FIELD-NAME
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        default:
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
            break;
        }

        if (getPrettyPrinting() && getIndentation() > 0) {
            gsonBuilder.setPrettyPrinting();
        }

        gsonBuilder.setDateFormat(options.getSimpleDateFormat());

        Set<FieldMapper> mappers = getFieldMappers();
        Map<Class, ClassMapper> classMappers = getClassMappers();
        List<ExclusionStrategy> strategies = new ArrayList<>();
        if (mappers != null) {
            gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
                @Override
                public String translateName(Field f) {
                    String fieldName = f.getName();
                    String serializedName = java2Json(f);
                    if (!fieldName.equalsIgnoreCase(serializedName)) {
                        // if null returned, this field is ignored
                        return serializedName;
                    }
                    return json2Java(f);
                }
            });

            for (FieldMapper mapper : mappers) {
                if (mapper.java == null || mapper.json == null || mapper.ignore) {
                    strategies.add(new ExclusionStrategy() {

                        @Override
                        public boolean shouldSkipField(FieldAttributes f) {
                            String name = f.getName();
                            Class cls = f.getClass();

                            if (mapper.java == null) {
                                if (mapper.json.equals(name)) {
                                    if (mapper.getType() == null || cls.equals(mapper.getType())) {
                                        return true;
                                    }
                                }

                            } else if (mapper.json == null || mapper.ignore) {
                                if (mapper.java.equals(name)) {
                                    if (mapper.getType() == null || cls.equals(mapper.getType())) {
                                        return true;
                                    }
                                }

                            }

                            return false;
                        }

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

        if (classMappers != null) {
            for (Entry<Class, ClassMapper> entry : classMappers.entrySet()) {
                ClassMapper mapper = entry.getValue();
                if (mapper.getType() == null) {
                    mapper.setType(entry.getKey());
                }
                if (mapper.ignore != null && mapper.ignore) {
                    strategies.add(new ExclusionStrategy() {

                        @Override
                        public boolean shouldSkipField(FieldAttributes f) {
                            return false;
                        }

                        @Override
                        public boolean shouldSkipClass(Class<?> clazz) {
                            if (clazz.equals(mapper.getType())) {
                                return true;
                            }
                            return false;
                        }
                    });
                }
            }

            for (Entry<Class, ClassMapper> entry : classMappers.entrySet()) {
                ClassMapper mapper = entry.getValue();
                if (!mapper.ignore && mapper.constructor != null) {
                    gsonBuilder.registerTypeAdapter(entry.getKey(), mapper.constructor);
                }
            }
        }

        int size = strategies.size();
        if (size > 0) {
            gsonBuilder.setExclusionStrategies(strategies.toArray(new ExclusionStrategy[size]));
        }

        Double version = getVersion();
        if (version != null) {
            gsonBuilder.setVersion(version);
        }

        if (isUseGsonExpose()) {
            gsonBuilder.excludeFieldsWithoutExposeAnnotation();
        }

        if (!DefaultValue.isDefault(getPatterns())) {
            gsonBuilder.setLenient();
        }

        gson = gsonBuilder.create();
    }

    return gson;
}

From source file:com.appslandia.common.json.GsonProcessor.java

License:Open Source License

public static GsonBuilder newBuilder() {
    GsonBuilder builder = new GsonBuilder();
    builder.setExclusionStrategies(new ExclusionStrategy() {

        @Override//from w  ww.  j  a v  a  2 s. c om
        public boolean shouldSkipField(FieldAttributes attrs) {
            return attrs.getAnnotation(NotBind.class) != null;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    });
    builder.registerTypeAdapter(java.util.Date.class, new DateAdapter());
    builder.registerTypeAdapter(java.sql.Date.class, new SqlDateAdapter());
    builder.registerTypeAdapter(java.sql.Time.class, new SqlTimeAdapter());
    builder.registerTypeAdapter(java.sql.Timestamp.class, new SqlDateTimeAdapter());
    return builder;
}

From source file:com.ecwid.mailchimp.internal.gson.MailChimpGsonFactory.java

License:Apache License

/**
 * Creates a new {@link Gson} object.//from   w ww.ja v a2 s .c  o m
 */
public static Gson createGson() {
    GsonBuilder builder = new GsonBuilder();
    builder.setExclusionStrategies(exclusionStrategy);
    builder.registerTypeAdapter(Date.class, new DateTypeAdapter());
    builder.registerTypeAdapterFactory(MailChimpObjectTypeAdapter.FACTORY);
    return builder.create();
}

From source file:com.gitblit.manager.FilestoreManager.java

License:Apache License

private static Gson gson(ExclusionStrategy... strategies) {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Date.class, new GmtDateTypeAdapter());
    if (!ArrayUtils.isEmpty(strategies)) {
        builder.setExclusionStrategies(strategies);
    }/*w  ww  . j  a va2 s .  com*/
    return builder.create();
}

From source file:com.gitblit.tickets.TicketSerializer.java

License:Apache License

public static Gson gson(ExclusionStrategy... strategies) {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Date.class, new GmtDateTypeAdapter());
    builder.registerTypeAdapter(Score.class, new ScoreTypeAdapter());
    if (!ArrayUtils.isEmpty(strategies)) {
        builder.setExclusionStrategies(strategies);
    }//from   w ww.  j  a  v a2 s.  c  o m
    return builder.create();
}

From source file:com.gitblit.utils.JsonUtils.java

License:Apache License

public static Gson gson(ExclusionStrategy... strategies) {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Date.class, new GmtDateTypeAdapter());
    builder.registerTypeAdapter(AccessPermission.class, new AccessPermissionTypeAdapter());
    if (!ArrayUtils.isEmpty(strategies)) {
        builder.setExclusionStrategies(strategies);
    }/* w  w  w. j  ava 2  s  . c  o  m*/
    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/*from ww w .jav a 2s .com*/
        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.indicator_engine.model.admin.GLAOperationsJSONObj.java

License:Open Source License

static Gson createGsonFromBuilder(ExclusionStrategy exs) {
    GsonBuilder gsonbuilder = new GsonBuilder();
    gsonbuilder.setExclusionStrategies(exs);
    return gsonbuilder.serializeNulls().create();
}

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.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  w  w w  .  ja v  a  2 s  . c  o m*/
    }

    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));
        }
    });
}