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:at.ac.uniklu.mobile.sportal.api.UnikluApiClient.java

License:Open Source License

private void init() {
    // init http client
    int timeout = 20000;
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setSoTimeout(httpParams, timeout);
    mHttpClient = new DefaultHttpClient(httpParams);
    mHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        @Override/*from w  w  w  .j  a  v  a2  s . c  om*/
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            logDebug("request retry " + executionCount + ": " + exception.getClass().getName());
            if (executionCount < 3) {
                if (exception instanceof SSLException) {
                    return true;
                }
                if (exception instanceof SocketTimeoutException) {
                    return true;
                }
                if (exception instanceof ConnectTimeoutException) {
                    return true;
                }
            }
            return false;
        }
    });

    // init gson & configure it to match server's output format
    mGson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
            .registerTypeAdapter(Notification.Type.class, new GsonNotificationTypeDeserializer()).create();
}

From source file:at.maui.cheapcast.chromecast.SessionSocket.java

License:Apache License

public SessionSocket(CheapCastService service, App app) {
    mService = service;//from   w ww  . j av  a 2s .c  om
    mApp = app;
    mContext = service;
    mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);

    mGson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .registerTypeAdapter(ProtocolMessage.class, new ProtocolMessageDeserializer())
            .registerTypeAdapter(ProtocolMessage.class, new ProtocolMessageSerializer())
            .registerTypeAdapter(RampMessage.class, new RampMessageDeserializer())
            .registerTypeAdapter(CmMessage.class, new CmMessageDeserializer()).create();
}

From source file:at.maui.cheapcast.chromecast.SystemControlSocket.java

License:Apache License

public SystemControlSocket(Context ctx) {
    mContext = ctx;//from  w  w w.ja v  a 2s  .c  o  m
    mAudioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
    mGson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
}

From source file:at.maui.gradle.plugin.imgcat.ImgcatTask.java

License:Open Source License

@TaskAction
public void imgcat() {
    ImgcatExtension extension = getProject().getExtensions().findByType(ImgcatExtension.class);
    if (extension == null) {
        extension = new ImgcatExtension();
    }//from  w w w  . j  av  a2 s. c  om

    if (extension.getSource().equals(ImgcatExtension.SOURCE_GIPHY)) {

        try {
            URL giphyUrl = null;
            if (extension.getValue() == null) {
                giphyUrl = new URL(GIPHY_API_BASE_URL);
            } else {
                giphyUrl = new URL(GIPHY_API_BASE_URL + "&tag=" + extension.getValue());
            }

            Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                    .create();

            GiphyResponse giphyResponse = gson.fromJson(new String(Utils.fetchUrl(giphyUrl)),
                    GiphyResponse.class);
            System.out.println(Imgcat.output("giphy.gif", true,
                    Utils.fetchUrl(new URL(giphyResponse.getData().getImageUrl()))));
            System.out.println("Powered By Giphy (http://www.giphy.com)");

        } catch (Exception ex) {
            System.out.println("Could'nt imgcat random giphy image");
        }
    } else if (extension.getSource().equals(ImgcatExtension.SOURCE_FILE)) {
        try {
            File localFile = new File(extension.getValue());

            System.out.println(Imgcat.output(localFile.getName(), true, Utils.fetchFile(localFile)));
        } catch (IOException e) {
            System.out.println("Could'nt imgcat local file at " + extension.getValue());
        }
    } else if (extension.getSource().equals(ImgcatExtension.SOURCE_REMOTE)) {
        try {
            System.out
                    .println(Imgcat.output("remote.gif", true, Utils.fetchUrl(new URL(extension.getValue()))));
        } catch (IOException e) {
            System.out.println("Could'nt imgcat remote with URL " + extension.getValue());
        }
    }
}

From source file:br.gov.jfrj.siga.ex.bl.ExBL.java

License:Open Source License

public String toJSON(ExMobil mobil) throws Exception {
    // Prune//from  w  ww . j  ava  2  s .c o  m
    ExMobil mob = (ExMobil) getImplementationDeep(mobil);

    // mob.setExDocumento((ExDocumento)
    // Objeto.getImplementation(mob.doc()));
    mob.setExDocumentoFilhoSet(null);
    // mob.setExMarcaSet(null);
    mob.setExMovimentacaoReferenciaSet(null);
    mob.setExMovimentacaoSet(null);
    mob.setExTipoMobil(null);

    ExDocumento doc = mob.doc();
    // doc.setCadastrante(null);
    // doc.setDestinatario(null);
    doc.setExBoletimDocSet(null);
    doc.setExClassificacao(null);
    doc.setExDocAnterior(null);
    doc.setExFormaDocumento(null);
    doc.setExMobilAutuado(null);
    doc.setExMobilPai(null);
    doc.setExMobilSet(null);
    doc.setExModelo(null);
    doc.setExNivelAcesso(null);
    // doc.setExTipoDocumento(null);
    // doc.getExTipoDocumento().setExFormaDocumentoSet(null);
    doc.setLotaCadastrante(null);
    doc.setLotaDestinatario(null);
    // doc.setLotaSubscritor((DpLotacao)
    // Objeto.getImplementation(doc.getLotaSubscritor()));
    // doc.setLotaSubscritor(null);
    // doc.setLotaTitular(null);
    // doc.setCadastrante(null);
    // doc.setDestinatario(null);
    // doc.setSubscritor(null);
    // doc.setTitular(null);
    // doc.setOrgaoExterno(null);
    // doc.setOrgaoExternoDestinatario(null);
    // doc.setOrgaoUsuario(null);

    ObjetoBaseSerializer hps = new ObjetoBaseSerializer();

    Gson gson = new GsonBuilder().registerTypeAdapter(java.sql.Blob.class, new BlobSerializer())
            // .registerTypeAdapter(ObjetoBase.class, hps)
            .setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    hps.setGson(gson);

    String jsonOutput = gson.toJson(mob);

    // Importante para que as alteraes do "prune" no sejam salvas no BD.
    dao().getSessao().clear();

    return jsonOutput;
}

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 2s.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:ca.tokenize.sally.api.SallyService.java

License:Open Source License

private static <T> T buildService(String baseUrl, String authToken, Class<T> service) {
    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .registerTypeAdapter(Date.class, new DateDeserializer()).create();

    AuthInterceptor interceptor = new AuthInterceptor(authToken);

    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(baseUrl)
            .setConverter(new GsonConverter(gson)).setRequestInterceptor(interceptor)
            .setErrorHandler(new SallyErrorHandler()).build();

    return restAdapter.create(service);
}

From source file:cd.go.contrib.elasticagents.docker.Agent.java

License:Apache License

public static String toJSONArray(Collection<Agent> metadata) {
    return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create()
            .toJson(metadata);/*  www . j  av a  2s  .co m*/
}

From source file:click.kobaken.rxirohaandroid.di.IrohaModule.java

License:Open Source License

private Gson createGson() {
    return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .registerTypeAdapter(Date.class, new DateTypeAdapter()).create();
}

From source file:co.cask.cdap.passport.http.client.PassportClient.java

License:Apache License

/**
 * Get List of VPC for the apiKey.//  w ww .  java  2 s . c  o m
 * @return Instance of {@code AccountProvider}
 * */
public AccountProvider<Account> getAccount(String apiKey) {
    Preconditions.checkNotNull(apiKey, "ApiKey cannot be null");

    try {
        Account account = accountCache.getIfPresent(apiKey);
        if (account == null) {
            String data = httpGet(API_BASE + "whois", apiKey);
            if (data != null) {
                Gson gson = new GsonBuilder()
                        .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                account = gson.fromJson(data, Account.class);
                accountCache.put(apiKey, account);
                return new AccountProvider<Account>(account);
            }
        } else {
            return new AccountProvider<Account>(account);
        }
        // This is a hack for overriding accountId type to String.
        // Ideally Account should use String type for account id instead
        return new AccountProvider<Account>(null);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    }
}