Example usage for com.google.gson GsonBuilder GsonBuilder

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

Introduction

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

Prototype

public GsonBuilder() 

Source Link

Document

Creates a GsonBuilder instance that can be used to build Gson with various configuration settings.

Usage

From source file:br.itecbrazil.serviceftpcliente.model.ArquivoDao.java

public void save(int tipo, ArrayList<Arquivo> arquivos) throws IOException {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    File arquivo;/*from w w w .  j ava  2  s.c o m*/
    if (tipo == EnumTipoArquivo.Envio.getTipoDoArquivo()) {
        arquivo = new File(EnumDiretorio.Configuracao.getDiretorio().concat(File.separator)
                .concat(EnumArquivos.Envio.getNomeDoArquivo()));
        persistir(gson.toJson(arquivos), arquivo);
    } else if (tipo == EnumTipoArquivo.Retorno.getTipoDoArquivo()) {
        arquivo = new File(EnumDiretorio.Configuracao.getDiretorio().concat(File.separator)
                .concat(EnumArquivos.Retorno.getNomeDoArquivo()));
        persistir(gson.toJson(arquivos), arquivo);
    } else {
        throw new IllegalArgumentException("Tipo de arquivo " + tipo + " invlido");
    }
}

From source file:br.jpe.dallahits.util.GsonUtils.java

/**
 * Instancia o Gson//w  ww.j  a  v  a2s . co  m
 */
private static synchronized void instantiate() {
    // Realiza double-checked locking para evitar problemas de concorrncia
    if (gson == null) {
        gson = new GsonBuilder().setDateFormat("dd/MM/yyyy").create();
    }
}

From source file:br.net.localizae.webservice.converter.JsonConverter.java

public static Object convertFromJson(String json, Class clazz) {
    Gson gson = new GsonBuilder().create();

    Object entity = gson.fromJson(json, clazz);

    return entity;
}

From source file:br.ufg.inf.es.fs.contpatri.mobile.tombamento.TombamentoDAO.java

License:GNU General Public License

/**
 * Retorna todos os registros da base de dados e os colocar em uma
 * <code>String</code> no formato JSON. Tal formato, ir ser tratado e ir
 * ser identado conforme JSON./*from ww w  . j av a2s .  com*/
 * 
 * @return retorna uma <code>String</code> que representa todos os objetos
 *         da base de dados
 */
public String getTodosJson() {
    return new GsonBuilder().setPrettyPrinting().create().toJson(getTodos().toArray());
}

From source file:br.ufg.inf.es.fs.contpatri.persistencia.JsonUtil.java

License:GNU General Public License

public JsonUtil() {
    gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
}

From source file:br.ufg.inf.es.saep.sandbox.dominio.infraestrutura.Serializador.java

License:Creative Commons License

/**
 * Cria instncia de serializar preparada
 * para realizar converses entre objetos e
 * sequncias de caracters./*from www .  ja  v  a 2  s. c o m*/
 */
public Serializador() {
    GsonBuilder gb = new GsonBuilder();
    gb.registerTypeAdapter(Valor.class, new ValorSerializer());
    gb.registerTypeAdapter(Valor.class, new ValorDeserializer());
    gson = gb.create();

    valorType = new TypeToken<Valor>() {
    }.getType();
    pontuacaoType = new TypeToken<Pontuacao>() {
    }.getType();
}

From source file:br.ufmg.hc.telessaude.webservices.mobile.utils.GsonUtils.java

public static Gson getInstanceWithStringDateAdapter() {
    GsonBuilder builder = new GsonBuilder();
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    //        final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a");
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        @Override/*from  w w  w .  j  a v a2  s  . co  m*/
        public Date deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
                throws JsonParseException {
            String data_str = "";
            Date data = null;
            try {
                data_str = je.getAsJsonPrimitive().getAsString();
                if (data_str.replaceAll("[\\-\\d]", "").isEmpty()) {
                    data = new Date(Long.parseLong(data_str));

                } else {
                    if (data_str.length() == 12) {
                        data = new SimpleDateFormat("MMM dd, yyyy").parse(data_str);
                    } else if (data_str.length() == 11) {
                        data = new SimpleDateFormat("MMM d, yyyy").parse(data_str);
                    } else if (data_str.length() == 10) {
                        data = new SimpleDateFormat("dd/MM/yyyy").parse(data_str);
                    } else {

                        data = sdf.parse(data_str);
                    }
                }
            } catch (ParseException ex) {
                Logger.getLogger(GsonUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
            return data;
        }
    });
    builder.registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
        @Override
        public JsonElement serialize(Date t, Type type, JsonSerializationContext jsc) {
            if (t == null) {
                return new JsonPrimitive((String) null);
            }
            return new JsonPrimitive(sdf.format(t));
        }
    });

    builder.registerTypeAdapter(java.sql.Date.class, new JsonSerializer<java.sql.Date>() {
        @Override
        public JsonElement serialize(java.sql.Date t, Type type, JsonSerializationContext jsc) {
            if (t == null) {
                return new JsonPrimitive((String) null);
            }
            return new JsonPrimitive(sdf.format(t));
        }
    });
    return builder.create();
}

From source file:br.unicamp.cst.bindings.soar.SOARPlugin.java

License:Open Source License

public String toPrettyFormat(JsonObject json) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String prettyJson = gson.toJson(json);
    return prettyJson;
}

From source file:br.univali.visao.JGraph.java

public void showHTML() throws Exception {
    Map<String, List> map1 = new HashMap<>();

    List<Map<String, String>> entrada = new ArrayList<>();

    for (int i = 0; i < this.points.size(); i++) {
        Map<String, String> pontosEntrada = new HashMap<>();
        pontosEntrada.put("x", this.points.get(i).getX().toString());
        pontosEntrada.put("y", this.points.get(i).getY().toString());

        entrada.add(pontosEntrada);//from w  w  w  . j  a  v  a  2 s. co  m
    }

    List<Map<String, String>> saida = new ArrayList<>();

    for (int i = 0; i < this.calculatedPoints.size(); i++) {
        Map<String, String> pontosSaida = new HashMap<>();
        pontosSaida.put("x", this.calculatedPoints.get(i).getX().toString());
        pontosSaida.put("y", this.calculatedPoints.get(i).getY().toString());

        saida.add(pontosSaida);
    }

    map1.put("dados", entrada);
    map1.put("calculados", saida);

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String code = gson.toJson(map1);

    String html = lerHtml("./src/br/univali/template/template.html");

    File pastaTemp = new File("./src/br/univali/template");
    File arquivoHtml = getRelatorio();
    File arquivoLog = getJsLog();

    html = html.replace("href=\"./", "href=\"file:///" + getCaminhoCompleto(pastaTemp) + "/");
    html = html.replace("src=\"./log.js\"", "src=\"file:///" + getCaminhoCompleto(arquivoLog) + "\"");
    html = html.replace("src=\"./", "src=\"file:///" + getCaminhoCompleto(pastaTemp) + "/");

    gravarArquivo(arquivoLog, "var log = " + code + ";");
    gravarArquivo(arquivoHtml, html);

    Desktop.getDesktop().open(arquivoHtml);

}

From source file:brooklyn.entity.chef.ChefTasks.java

License:Apache License

public static TaskFactory<?> buildChefFile(String runDirectory, String chefDirectory, String phase,
        Iterable<? extends String> runList, Map<String, Object> optionalAttributes) {
    // TODO if it's server, try knife first
    // TODO configure add'l properties
    String phaseRb = "root = " + "'" + runDirectory + "'"
    // recommended alternate to runDir is the following, but it is not available in some rubies
    //+ File.absolute_path(File.dirname(__FILE__))"+
            + "\n" + "file_cache_path root\n" +
            //            "cookbook_path root + '/cookbooks'\n";
            "cookbook_path '" + chefDirectory + "'\n";

    Map<String, Object> phaseJsonMap = MutableMap.of();
    if (optionalAttributes != null)
        phaseJsonMap.putAll(optionalAttributes);
    if (runList != null)
        phaseJsonMap.put("run_list", ImmutableList.copyOf(runList));
    Gson json = new GsonBuilder().create();
    String phaseJson = json.toJson(phaseJsonMap);

    return Tasks.sequential("build chef files for " + phase,
            SshEffectorTasks.put(Urls.mergePaths(runDirectory) + "/" + phase + ".rb").contents(phaseRb)
                    .createDirectory(),/*from   w w w . j  a v a  2  s  .  co  m*/
            SshEffectorTasks.put(Urls.mergePaths(runDirectory) + "/" + phase + ".json").contents(phaseJson));
}