Example usage for com.google.gson FieldNamingStrategy FieldNamingStrategy

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

Introduction

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

Prototype

FieldNamingStrategy

Source Link

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:/*from ww  w.jav  a  2 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.github.api.v2.services.impl.BaseGitHubService.java

License:Apache License

/**
 * Gets the gson builder.//from   ww  w.jav  a2 s .c om
 * 
 * @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 w w  w  .  j  av a 2  s .com*/
        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   www .  jav a  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.//  w  w  w .  ja v  a2  s .c  om
 *
 * @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:org.ebayopensource.scc.track.TrackerClient.java

License:Apache License

protected HttpEntity createEntity(Object pojo) {
    Gson gson = new GsonBuilder().serializeNulls().setFieldNamingStrategy(new FieldNamingStrategy() {

        @Override//from   w ww . j ava2  s  . co  m
        public String translateName(Field field) {
            String name = field.getName();
            if (name.startsWith("m_")) {
                name = name.substring(2);
            }
            return name;
        }
    }).create();
    return new StringEntity(gson.toJson(pojo), ContentType.APPLICATION_JSON);
}

From source file:org.unitime.timetable.api.JsonApiHelper.java

License:Apache License

protected Gson createGson() {
    return new GsonBuilder()
            .registerTypeAdapter(java.sql.Timestamp.class, new JsonSerializer<java.sql.Timestamp>() {
                @Override// ww  w . j a v a2 s  .c  o  m
                public JsonElement serialize(java.sql.Timestamp src, Type typeOfSrc,
                        JsonSerializationContext context) {
                    return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src));
                }
            }).registerTypeAdapter(java.sql.Date.class, new JsonSerializer<java.sql.Date>() {
                @Override
                public JsonElement serialize(java.sql.Date src, Type typeOfSrc,
                        JsonSerializationContext context) {
                    return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd").format(src));
                }
            }).registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
                @Override
                public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
                    return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src));
                }
            }).setFieldNamingStrategy(new FieldNamingStrategy() {
                Pattern iPattern = Pattern.compile("i([A-Z])(.*)");

                @Override
                public String translateName(Field f) {
                    Matcher matcher = iPattern.matcher(f.getName());
                    if (matcher.matches())
                        return matcher.group(1).toLowerCase() + matcher.group(2);
                    else
                        return f.getName();
                }
            }).setPrettyPrinting().create();
}

From source file:org.unitime.timetable.export.events.EventsExportEventsToJSON.java

License:Apache License

@Override
protected void print(ExportHelper helper, EventLookupRpcRequest request, List<EventInterface> events,
        int eventCookieFlags, EventMeetingSortBy sort, boolean asc) throws IOException {
    helper.setup("application/json", reference(), false);

    Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
        @Override/*from w w  w. j a  v a2 s .c  o m*/
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src));
        }
    }).setFieldNamingStrategy(new FieldNamingStrategy() {
        Pattern iPattern = Pattern.compile("i([A-Z])(.*)");

        @Override
        public String translateName(Field f) {
            Matcher matcher = iPattern.matcher(f.getName());
            if (matcher.matches())
                return matcher.group(1).toLowerCase() + matcher.group(2);
            else
                return f.getName();
        }
    }).setPrettyPrinting().create();

    helper.getWriter().write(gson.toJson(events));
}

From source file:org.unitime.timetable.export.rooms.RoomsExportJSON.java

License:Apache License

@Override
protected void print(ExportHelper helper, List<RoomDetailInterface> rooms, ExportContext context)
        throws IOException {
    helper.getSessionContext().checkPermission(Right.RoomsExportJson);

    helper.setup("application/json", reference(), false);

    Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
        @Override/*  w  w  w. j  a v  a 2 s  .co m*/
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src));
        }
    }).setFieldNamingStrategy(new FieldNamingStrategy() {
        Pattern iPattern = Pattern.compile("i([A-Z])(.*)");

        @Override
        public String translateName(Field f) {
            Matcher matcher = iPattern.matcher(f.getName());
            if (matcher.matches())
                return matcher.group(1).toLowerCase() + matcher.group(2);
            else
                return f.getName();
        }
    }).setPrettyPrinting().create();

    helper.getWriter().write(gson.toJson(rooms));
}

From source file:org.unitime.timetable.gwt.command.server.GwtRpcServlet.java

License:Apache License

@Override
public void init() throws ServletException {
    iSaver = new QueryLogFilter.Saver();
    iSaver.setName("GwtRpcLogSaver");
    iSaver.start();//w  w w  .  j  a  va 2  s .  com
    iGson = new GsonBuilder()
            .registerTypeAdapter(java.sql.Timestamp.class, new JsonSerializer<java.sql.Timestamp>() {
                @Override
                public JsonElement serialize(java.sql.Timestamp src, Type typeOfSrc,
                        JsonSerializationContext context) {
                    return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src));
                }
            }).registerTypeAdapter(java.sql.Date.class, new JsonSerializer<java.sql.Date>() {
                @Override
                public JsonElement serialize(java.sql.Date src, Type typeOfSrc,
                        JsonSerializationContext context) {
                    return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd").format(src));
                }
            }).registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
                @Override
                public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
                    return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src));
                }
            }).setFieldNamingStrategy(new FieldNamingStrategy() {
                Pattern iPattern = Pattern.compile("i([A-Z])(.*)");

                @Override
                public String translateName(Field f) {
                    Matcher matcher = iPattern.matcher(f.getName());
                    if (matcher.matches())
                        return matcher.group(1).toLowerCase() + matcher.group(2);
                    else
                        return f.getName();
                }
            }).create();
}