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:ce2mapper.HTMLbuilder.java

private void createJSON() throws IOException {

    //Gson gson = new Gson();
    prepareListForJSON();/*from  ww  w.j  ava 2s. c  om*/
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(jsonList);

    String path = System.getProperty("user.dir") + File.separator + "HTML_SET" + File.separator
            + "index01.json";

    FileWriter writer = new FileWriter(path);//"d:\\file.json");
    writer.write(json);
    writer.close();
}

From source file:cern.c2mon.shared.util.json.GsonFactory.java

License:Open Source License

/**
 * Creates a Gson Builder that converts by default a time stamp to a long
 * value. Furthermore, in case of an <code>Object</code> field it does not
 * try to deserialize the object but stores instead the Json String to that
 * field. The deserialization has then to be handled in an extra step once the
 * final Object class information is available. 
 * @return The Gson Builder to serialize/deserialize Json messages
 */// ww  w.j  av  a  2  s  .  c  o m
public static GsonBuilder createGsonBuilder() {
    GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampSerializer())
            .registerTypeAdapter(Timestamp.class, new TimestampDeserializer())
            .registerTypeAdapter(Object.class, new TagValueDeserializer());

    return gsonBuilder;
}

From source file:cf.funge.aworldofplants.action.AbstractAction.java

License:Open Source License

/**
 * Returns an initialized Gson object with the default configuration
 * @return An initialized Gson object/* w w w.  j  av a 2  s  .  c  o  m*/
 */
protected Gson getGson() {
    return new GsonBuilder()
            //.enableComplexMapKeySerialization()
            //.serializeNulls()
            //.setDateFormat(DateFormat.LONG)
            //.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
            .setPrettyPrinting().create();
}

From source file:ch.admin.suis.msghandler.servlet.MonitorServlet.java

License:Open Source License

private String toJson(Object obj, Class c) {
    GsonBuilder gsonBilder = new GsonBuilder();
    Gson gson = gsonBilder.create();

    return gson.toJson(obj, c);
}

From source file:ch.berta.fabio.popularmovies.data.rest.MovieDbClient.java

License:Apache License

/**
 * Returns a custom date deserializer that handles empty strings and returns today's date instead.
 *
 * @return the Gson object to use// w w w .  j a  v  a  2s . com
 */
private static Gson getGsonObject() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        final DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US);

        @Override
        public Date deserialize(final JsonElement json, final Type typeOfT,
                final JsonDeserializationContext context) throws JsonParseException {
            try {
                return dateFormat.parse(json.getAsString());
            } catch (ParseException e) {
                return new Date();
            }
        }
    });

    return gsonBuilder.create();
}

From source file:ch.cyclops.util.PrettyGson.java

License:Open Source License

private static Gson getGson() {
    return new GsonBuilder().setPrettyPrinting().create();
}

From source file:ch.devmine.javaparser.utils.GsonFactory.java

License:Open Source License

public static Gson build() {
    GsonBuilder builder = new GsonBuilder();
    builder.addSerializationExclusionStrategy(new ExclusionStrategy() {

        @Override//from   w ww  .j  a va  2 s  . c om
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getAnnotation(GsonTransient.class) != null;
        }

        @Override
        public boolean shouldSkipClass(Class<?> c) {
            return c.getAnnotation(GsonTransient.class) != null;
        }
    });
    return builder.create();
}

From source file:ch.digitalfondue.jfiveparse.GenerateEntities.java

License:Apache License

public static void main(String[] args) throws IOException {
    Type type = (new TypeToken<Map<String, EntityValues>>() {
    }).getType();//  ww w .  j a va  2  s  .  c om
    String json = new String(Files.readAllBytes(Paths.get("src/test/resources/entities.json")),
            StandardCharsets.UTF_8);
    Map<String, EntityValues> m = new GsonBuilder().create().fromJson(json, type);

    Prefix p = new Prefix(null);

    ByteArrayOutputStream baosOneCodePoint = new ByteArrayOutputStream();
    GZIPOutputStream osOneCodePoint = new GZIPOutputStream(baosOneCodePoint);
    DataOutputStream daos = new DataOutputStream(osOneCodePoint);

    int oneCodePointLength = 0;
    int twoCodePointLength = 0;

    for (String key : m.keySet()) {
        p.addWord(key, m.get(key).codepoints);

        if (m.get(key).codepoints.length == 1) {
            oneCodePointLength++;
            daos.writeUTF(key);
            daos.writeInt(m.get(key).codepoints[0]);
        }

        if (m.get(key).codepoints.length > 2) {
            throw new IllegalStateException("more than 2 codepoints");
        }
    }

    for (String key : m.keySet()) {
        if (m.get(key).codepoints.length == 2) {
            twoCodePointLength++;
            daos.writeUTF(key);
            daos.writeInt(m.get(key).codepoints[0]);
            daos.writeInt(m.get(key).codepoints[1]);
        }
    }

    daos.flush();
    daos.close();

    System.err.println(oneCodePointLength);
    System.err.println(twoCodePointLength);

    Files.write(Paths.get("entities-with-1-2-codepoint"), baosOneCodePoint.toByteArray());
}

From source file:ch.eitchnet.csvrestendpoint.resources.CsvResource.java

License:Apache License

@GET
@Produces(MediaType.APPLICATION_JSON)/*www  .j  a  v  a  2 s  .c  o m*/
@Consumes(MediaType.APPLICATION_JSON)
public Response getNames() {

    logger.info("Received request for names.");

    try {

        CsvDataHandler csvDataHandler = RestfulStrolchComponent.getInstance()
                .getComponent(CsvDataHandler.class);
        List<String> names = csvDataHandler.getCsvNames();

        CsvNamesToJsonMarshaller marshaller = new CsvNamesToJsonMarshaller();
        JsonObject root = marshaller.marshall(names);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String entity = gson.toJson(root);

        return Response.ok(entity, MediaType.APPLICATION_JSON).build();

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        Result result = new Result(ExceptionHelper.getExceptionMessage(e));
        String entity = new Gson().toJson(result);
        return Response.ok(entity, MediaType.APPLICATION_JSON).build();
    }
}

From source file:ch.eitchnet.csvrestendpoint.resources.CsvResource.java

License:Apache License

private Response queryData(String name, CsvDataMarshaller<JsonObject> marshaller) {

    CsvDataHandler csvDataHandler = RestfulStrolchComponent.getInstance().getComponent(CsvDataHandler.class);
    JsonObject root = csvDataHandler.getCsvData(name, marshaller);
    if (root == null)
        throw new RuntimeException("No CSV Data exists with name '" + name + "'");

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String entity = gson.toJson(root);

    return Response.ok(entity, MediaType.APPLICATION_JSON_TYPE.withCharset(marshaller.getCharset().name()))
            .build();//  w w  w. ja  v a 2s  . c o m
}