Example usage for com.google.gson GsonBuilder setFieldNamingStrategy

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

Introduction

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

Prototype

public GsonBuilder setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy) 

Source Link

Document

Configures Gson to apply a specific naming policy strategy to an object's field during 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 v  a2  s.co 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.eclipsesource.connect.serialization.GsonFactory.java

License:Open Source License

private static void addFieldNamingStrategy(GsonBuilder builder) {
    builder.setFieldNamingStrategy(field -> {
        if (field.getType() == Id.class) {
            return KEY_ID;
        }//from  w  w w.j av  a  2s  . co  m
        if (field.isAnnotationPresent(Name.class)) {
            return field.getAnnotation(Name.class).value();
        }
        return field.getName();
    });
}

From source file:com.github.api.v2.services.impl.BaseGitHubService.java

License:Apache License

/**
 * Gets the gson builder./*from   w  w w.  j  a  va2  s  .  co m*/
 * 
 * @return the gson builder
 */
protected GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();
    builder.setDateFormat(ApplicationConstants.DATE_FORMAT);
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    builder.setFieldNamingStrategy(new FieldNamingStrategy() {
        @Override
        public String translateName(Field field) {
            if (field.getType().equals(Repository.Visibility.class)) {
                return "private";
            } else if (field.getType().equals(Gist.Visibility.class)) {
                return "public";
            } else {
                return field.getName();
            }
        }

    });
    builder.registerTypeAdapter(Issue.State.class, new JsonDeserializer<Issue.State>() {
        @Override
        public Issue.State deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return Issue.State.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Repository.Visibility.class, new JsonDeserializer<Repository.Visibility>() {
        @Override
        public Repository.Visibility deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return (arg0.getAsBoolean()) ? Repository.Visibility.PRIVATE : Repository.Visibility.PUBLIC;
        }
    });
    builder.registerTypeAdapter(Gist.Visibility.class, new JsonDeserializer<Gist.Visibility>() {
        @Override
        public Gist.Visibility deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return (arg0.getAsBoolean()) ? Gist.Visibility.PUBLIC : Gist.Visibility.PRIVATE;
        }
    });
    builder.registerTypeAdapter(Language.class, new JsonDeserializer<Language>() {
        @Override
        public Language deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return Language.fromValue(arg0.getAsString());
        }
    });
    builder.registerTypeAdapter(Tree.Type.class, new JsonDeserializer<Tree.Type>() {
        @Override
        public Tree.Type deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return Tree.Type.fromValue(arg0.getAsString());
        }
    });
    return builder;
}

From source file:com.liferay.music.portlet.util.MusicFiles.java

License:Open Source License

public static Gson getGson() {
    FieldNamingStrategy customPolicy = new FieldNamingStrategy() {

        @Override//from  www.j a v a 2  s . co  m
        public String translateName(Field field) {
            String name = field.getName();

            return name.substring(1);
        }
    };

    GsonBuilder gsonBuilder = new GsonBuilder();

    gsonBuilder.setFieldNamingStrategy(customPolicy);

    return gsonBuilder.create();
}

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

License:Apache License

private static void markSetAndMapFields(final GsonBuilder gsonBuilder) {
    gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
        @Override/*from  w  w  w .  ja va 2s .  c o m*/
        public String translateName(Field f) {
            if (Set.class.isAssignableFrom(f.getType()) || Map.class.isAssignableFrom(f.getType())) {
                return MARKER + f.getName();
            }
            return f.getName();
        }
    });
}

From source file:edu.mayo.cts2.framework.core.json.JsonConverter.java

License:Open Source License

/**
 * Builds the gson./*from   ww w .jav  a2s  . c  o  m*/
 *
 * @return the gson
 */
protected Gson buildGson() {
    GsonBuilder gson = new GsonBuilder();

    gson.setDateFormat(ISO_DATE_FORMAT);

    gson.setExclusionStrategies(new ExclusionStrategy() {

        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getName().equals(CHOICE_VALUE);
        }

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

    });

    gson.registerTypeAdapter(List.class, new EmptyCollectionSerializer());
    gson.registerTypeAdapter(TsAnyType.class, new TsAnyTypeSerializer());
    gson.registerTypeAdapter(Date.class, new DateTypeAdapter());
    gson.registerTypeAdapterFactory(new ChangeableTypeAdapterFactory());
    gson.registerTypeAdapterFactory(new ChangeableResourceTypeAdapterFactory());

    gson.setFieldNamingStrategy(new FieldNamingStrategy() {

        @Override
        public String translateName(Field field) {
            String fieldName = field.getName();

            char[] array = fieldName.toCharArray();

            if (array[0] == '_') {
                array = ArrayUtils.remove(array, 0);
            }

            String name = new String(array);
            if (name.endsWith(LIST_SUFFIX)) {
                name = StringUtils.removeEnd(name, LIST_SUFFIX);
            }

            return name;
        }

    });

    return gson.create();
}

From source file:jetbrains.buildServer.sharedResources.server.report.UsedResourcesSerializer.java

License:Apache License

public List<UsedResource> read(@NotNull final Reader reader) {
    final GsonBuilder builder = new GsonBuilder();
    builder.setFieldNamingStrategy(STRATEGY);
    builder.registerTypeAdapter(Resource.class,
            (InstanceCreator<Resource>) type -> ResourceFactory.newInfiniteResource("", "", "", true));
    builder.registerTypeAdapter(Lock.class, (InstanceCreator<Lock>) type -> new Lock("", LockType.READ, ""));
    builder.registerTypeAdapterFactory(MY_TYPE_ADAPTER_FACTORY);
    return builder.setPrettyPrinting().create().fromJson(reader, new TypeToken<List<UsedResource>>() {
    }.getType());//w w  w  .j  av  a2 s  .  c o  m
}

From source file:jetbrains.buildServer.sharedResources.server.report.UsedResourcesSerializer.java

License:Apache License

public void write(Collection<UsedResource> usedResources, Writer writer) {
    final GsonBuilder builder = new GsonBuilder();
    builder.setFieldNamingStrategy(STRATEGY);
    builder.setPrettyPrinting();/*  w  ww.  ja  v  a  2 s.  co  m*/
    builder.create().toJson(usedResources, writer);
}

From source file:net.signalr.client.serialization.gson.GsonSerializer.java

License:Open Source License

private static Gson build() {
    GsonBuilder gsonBuilder = new GsonBuilder();

    gsonBuilder.excludeFieldsWithModifiers(Modifier.STATIC);
    gsonBuilder.setFieldNamingStrategy(new ReflectiveFieldNamingStrategy());

    return gsonBuilder.create();
}

From source file:org.apache.camel.component.gson.GsonDataFormat.java

License:Apache License

@Override
protected void doStart() throws Exception {
    if (gson == null) {
        GsonBuilder builder = new GsonBuilder();
        if (exclusionStrategies != null && !exclusionStrategies.isEmpty()) {
            ExclusionStrategy[] strategies = exclusionStrategies
                    .toArray(new ExclusionStrategy[exclusionStrategies.size()]);
            builder.setExclusionStrategies(strategies);
        }//from ww w. jav a  2 s  .  c o  m
        if (longSerializationPolicy != null) {
            builder.setLongSerializationPolicy(longSerializationPolicy);
        }
        if (fieldNamingPolicy != null) {
            builder.setFieldNamingPolicy(fieldNamingPolicy);
        }
        if (fieldNamingStrategy != null) {
            builder.setFieldNamingStrategy(fieldNamingStrategy);
        }
        if (serializeNulls != null && serializeNulls) {
            builder.serializeNulls();
        }
        if (prettyPrinting != null && prettyPrinting) {
            builder.setPrettyPrinting();
        }
        if (dateFormatPattern != null) {
            builder.setDateFormat(dateFormatPattern);
        }
        gson = builder.create();
    }
}