Example usage for com.google.gson FieldNamingPolicy LOWER_CASE_WITH_UNDERSCORES

List of usage examples for com.google.gson FieldNamingPolicy LOWER_CASE_WITH_UNDERSCORES

Introduction

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

Prototype

FieldNamingPolicy LOWER_CASE_WITH_UNDERSCORES

To view the source code for com.google.gson FieldNamingPolicy LOWER_CASE_WITH_UNDERSCORES.

Click Source Link

Document

Using this naming policy with Gson will modify the Java Field name from its camel cased form to a lower case field name where each word is separated by an underscore (_).

Usage

From source file:com.fmf.jersey.MesAmis.java

@GET
// Path: http://localhost/<appln-folder-name>/login/dologin
@Path("/add")
// Produces JSON as response
@Produces(MediaType.APPLICATION_JSON)/* ww  w. j  a v a2  s .c o  m*/
// Query parameters are parameters: http://localhost/<appln-folder-name>/login/dologin?username=abc&password=xyz
public String addAmi(@QueryParam("personne") String personne, @QueryParam("personneaajouter") String AAjouter) {
    String response = "";
    System.out.println("how you doing");
    Personne P = null;
    Personne P2 = null;
    Gson gson = new GsonBuilder().setPrettyPrinting().setDateFormat("MMM d, yyyy HH:mm:ss")
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    P = gson.fromJson(personne, Personne.class);
    P2 = gson.fromJson(AAjouter, Personne.class);
    P = personneFacade.find(P.getId());
    P2 = personneFacade.find(P2.getId());
    System.out.println(P2.getNom());
    DemandeAjoutPK A = new DemandeAjoutPK();
    A.setEmetteur(P.getId());
    A.setRecepteur(P2.getId());
    DemandeAjout amis = new DemandeAjout();
    amis.setDemandeAjoutPK(A);
    amis.setPersonne(P);
    amis.setPersonne1(P2);
    demandeAjoutFacade.create(amis);
    response = "added";
    System.out.println(response);
    return response;
}

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

License:Apache License

/**
 * Gets the gson builder./*  w  w w  . ja  va  2s  .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.google.code.stackexchange.client.impl.StackExchangeApiJsonClient.java

License:Apache License

protected GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        @Override/*from ww  w  . j ava2  s .c  o m*/
        public Date deserialize(JsonElement source, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return new Date(source.getAsLong() * 1000);
        }

    });
    builder.registerTypeAdapter(BadgeRank.class, new JsonDeserializer<BadgeRank>() {

        @Override
        public BadgeRank deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return BadgeRank.fromValue(arg0.getAsString());
        }

    });
    builder.registerTypeAdapter(PostType.class, new JsonDeserializer<PostType>() {

        @Override
        public PostType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return PostType.fromValue(arg0.getAsString());
        }

    });
    builder.registerTypeAdapter(PostTimelineType.class, new JsonDeserializer<PostTimelineType>() {

        @Override
        public PostTimelineType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return PostTimelineType.fromValue(arg0.getAsString());
        }

    });
    builder.registerTypeAdapter(UserTimelineType.class, new JsonDeserializer<UserTimelineType>() {

        @Override
        public UserTimelineType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return UserTimelineType.fromValue(arg0.getAsString());
        }

    });
    builder.registerTypeAdapter(UserType.class, new JsonDeserializer<UserType>() {

        @Override
        public UserType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return UserType.fromValue(arg0.getAsString());
        }

    });
    builder.registerTypeAdapter(RevisionType.class, new JsonDeserializer<RevisionType>() {

        @Override
        public RevisionType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return RevisionType.fromValue(arg0.getAsString());
        }

    });
    builder.registerTypeAdapter(TagRestriction.class, new JsonDeserializer<TagRestriction>() {

        @Override
        public TagRestriction deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return TagRestriction.fromValue(arg0.getAsString());
        }

    });
    builder.registerTypeAdapter(SiteState.class, new JsonDeserializer<SiteState>() {

        @Override
        public SiteState deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {
            return SiteState.fromValue(arg0.getAsString());
        }
    });

    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);

    return builder;
}

From source file:com.google.gerrit.elasticsearch.ElasticTestUtils.java

License:Apache License

private static String getHttpPort(Node node) throws InterruptedException, ExecutionException {
    String nodes = node.client().admin().cluster().nodesInfo(new NodesInfoRequest("*")).get().toString();
    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    Info info = gson.fromJson(nodes, Info.class);
    if (info.nodes == null || info.nodes.size() != 1) {
        throw new RuntimeException("Cannot extract local Elasticsearch http port");
    }/*from www  .  j a  va  2 s.c  o m*/
    Iterator<NodeInfo> values = info.nodes.values().iterator();
    String httpAddress = values.next().httpAddress;
    if (Strings.isNullOrEmpty(httpAddress)) {
        throw new RuntimeException("Cannot extract local Elasticsearch http port");
    }
    if (httpAddress.indexOf(':') < 0) {
        throw new RuntimeException("Seems that port is not included in Elasticsearch http_address");
    }
    return httpAddress.substring(httpAddress.indexOf(':') + 1, httpAddress.length());
}

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));
    }/*w w w.  ja  v  a2  s. co  m*/
    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.google.gerrit.server.OutputFormat.java

License:Apache License

/** @return a new Gson instance configured according to the format. */
public GsonBuilder newGsonBuilder() {
    if (!isJson()) {
        throw new IllegalStateException(String.format("%s is not JSON", this));
    }//from   w  w  w  .  j  a v a  2 s  .  c o m
    GsonBuilder gb = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .registerTypeAdapter(Timestamp.class, new SqlTimestampDeserializer());
    if (this == OutputFormat.JSON) {
        gb.setPrettyPrinting();
    }
    return gb;
}

From source file:com.google.gitiles.BaseServlet.java

License:Open Source License

@SuppressWarnings("unused") // Used in subclasses.
protected GsonBuilder newGsonBuilder(HttpServletRequest req) throws IOException {
    return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setPrettyPrinting().generateNonExecutableJson();
}

From source file:com.google.gitiles.HostIndexServlet.java

License:Open Source License

private void displayJson(HttpServletRequest req, HttpServletResponse res,
        Map<String, RepositoryDescription> descs) throws IOException {
    res.setContentType(JSON.getMimeType());
    res.setCharacterEncoding("UTF-8");
    res.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment");
    setNotCacheable(res);/*from w  w  w  . ja  v  a 2 s  .  c o  m*/

    PrintWriter writer = res.getWriter();
    new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setPrettyPrinting()
            .generateNonExecutableJson().create()
            .toJson(descs, new TypeToken<Map<String, RepositoryDescription>>() {
            }.getType(), writer);
    writer.print('\n');
    writer.close();
}

From source file:com.google.maps.ApiContext.java

License:Open Source License

public <T, R extends ApiResponse<T>> PendingResult<T> get(Class<R> clazz, String path,
        Map<String, String> params) {
    StringBuilder query = new StringBuilder();

    for (Map.Entry<String, String> param : params.entrySet()) {
        query.append('&').append(param.getKey()).append("=");
        try {/*from w  ww  .  java2  s. com*/
            query.append(URLEncoder.encode(param.getValue(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            return new ExceptionResult<T>(e);
        }
    }
    return getWithPath(clazz, FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES, path, query.toString());
}

From source file:com.google.maps.ApiContext.java

License:Open Source License

public <T, R extends ApiResponse<T>> PendingResult<T> get(Class<R> clazz, String path, String... params) {
    return get(clazz, FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES, path, params);
}