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:ca.live.hk12.numera.server.database.FileService.java

License:Open Source License

public static <T> T readData(String fileLocation, Class<T> dataClass) {
    T t = null;//w ww  .  java2 s . c  o  m
    try (Reader reader = new InputStreamReader(new FileInputStream(fileLocation), "UTF-8")) {
        Gson gson = new GsonBuilder().create();
        t = gson.fromJson(reader, dataClass);
        reader.close();
    } catch (Exception e) {
        return t;
    }
    return t;
}

From source file:ca.live.hk12.numera.server.database.FileService.java

License:Open Source License

public static <T> boolean writeData(String fileLocation, T t) {
    try (Writer writer = new OutputStreamWriter(new FileOutputStream(fileLocation), "UTF-8")) {
        Gson gson = new GsonBuilder().create();
        gson.toJson(t, writer);//from w  w  w. j a va 2 s  .c  o  m
        writer.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        throw new ServerException("Could not write to:<br/>" + fileLocation);
    }
}

From source file:ca.magenta.pi.remote.common.WiringPiReturnStatus.java

License:Apache License

public String returnJSonAsString(boolean pretty) {
    String r_string = null;// w w  w. ja va2s .c o m

    try {
        if (pretty) {
            r_string = (new GsonBuilder().setPrettyPrinting().create()).toJson(this);
        } else {
            r_string = (new Gson()).toJson(this);
        }

    } catch (Throwable e) {
        r_string = this.returnRuntimeExceptionJSonStr(e);
    }

    return r_string;
}

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 v 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:ca.thoughtfire.metastats.StatsServer.java

License:Open Source License

public static void main(final String[] args) throws Exception {

    Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();

    System.out.println("metaStats Core Server Version " + version.getBuildNumber() + " ("
            + version.getBuildName() + ") - Code By " + version.getAuthor());
    System.out.println("");
    OptionParser parser = new OptionParser("c:");
    parser.accepts("config").withRequiredArg();

    try {//from   ww  w.  j ava2s. com
        OptionSet options = parser.parse(args);

        String configFileName = options.valueOf("config").toString();
        File file = new File(configFileName);
        if ((!file.isFile()) || (!file.canRead())) {
            System.out.println("Error - cannot read configuration \"" + file + "\" - aborting.");
            System.exit(1);
        }
        try {
            String jsonInput = new String(readAllBytes(get(configFileName)));
            config = gson.fromJson(jsonInput, SystemConfiguration.class);

        } catch (IOException | JsonSyntaxException ex) {
            System.out.println("Error - cannot parse configuration \"" + file + "\" - error is \"" + ex
                    + "\" - aborting.");
            System.exit(1);
        }

    } catch (Exception ex) {
        System.out.println("Error processing command line arguments: " + ex);
        System.exit(1);
    }
    try {
        logger.addAppender(new DailyRollingFileAppender(new PatternLayout("%d{ISO8601} [%-5p] %m%n"),
                config.getLogDir() + "/" + config.getLogFileName(), "'.'yyyy-MM-dd"));
    } catch (Exception ex) {
        System.out.println("FATAL - COULD NOT SETUP LOG FILE APPENDER - CHECK CONFIGURATION.");
        logger.fatal("Could not setup appender?");
    }
    logger.setAdditivity(false);
    logger.setLevel(Level.DEBUG);

    logger.info("metaStats Core Server Version " + version.getBuildNumber() + " (" + version.getBuildName()
            + ") - Code By " + version.getAuthor());

    /* Light up database */
    Class.forName("org.postgresql.Driver"); // load the DB driver
    BoneCPConfig boneCPconfig = new BoneCPConfig(); // create a new configuration object
    boneCPconfig.setJdbcUrl("jdbc:postgresql://" + config.getDbServer() + "/" + config.getDbName()); // set the JDBC url
    boneCPconfig.setUsername(config.getDbUser()); // set the username
    boneCPconfig.setPassword(config.getDbPass()); // set the password

    logger.info("Database Connection Online");
    connectionPool = new BoneCP(boneCPconfig); // setup the connection pool

    Server server = new Server(config.getListenPort());
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);

    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    DefaultExports.initialize();

    logger.info("Creating timer thread to poll Metaswitch.");
    timer = new Timer();

    timer.schedule(dbTask, 300, 300 * 1000); // Run every 5 minutes
    logger.info("Timer created - ready to rock");

    // Put your application setup code here.
    server.start();
    server.join();
    logger.info("Listening on port " + config.getListenPort());

}

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:ca.tonsaker.workschedu.employee.Employee.java

License:Apache License

public boolean save() throws IOException {
    String path = System.getenv("APPDATA") + "\\WorkSchedU\\Employees\\user" + this.EMPLOYEE_USERNAME + ".json";
    new File(System.getenv("APPDATA") + "\\WorkSchedU\\Employees").mkdirs();
    Writer writer = new OutputStreamWriter(new FileOutputStream(path));
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();

    writer.write(gson.toJson(this));
    writer.flush();/*from w w  w  .j a  v a  2 s.  co m*/
    writer.close();

    System.out.println("Employee JSON file successfully saved to: " + path);
    return true;
}

From source file:ca.tonsaker.workschedu.employee.Employee.java

License:Apache License

public static Employee load(String username) throws FileNotFoundException {
    Employee e = new Employee();
    String path = System.getenv("APPDATA") + "\\WorkSchedU\\Employees\\user" + username + ".json";
    FileInputStream file = new FileInputStream(path);

    Reader reader = new InputStreamReader(file);
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();

    e = gson.fromJson(reader, Employee.class);
    return e;/*from w  ww  .  ja  va  2s.c om*/
}

From source file:ca.tonsaker.workschedu.employee.Employee.java

License:Apache License

public static Employee[] load() throws FileNotFoundException {
    String path = System.getenv("APPDATA") + "\\WorkSchedU\\Employees\\";
    File folder = new File(path);
    File[] listOfFiles = folder.listFiles();

    Employee[] temp_employeesArray = new Employee[listOfFiles.length];
    int empIdx = 0;
    for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].isFile()
                && listOfFiles[i].getName().substring(listOfFiles[i].getName().indexOf('.')).equals(".json")) {

            FileInputStream file = new FileInputStream(listOfFiles[i]);

            Reader reader = new InputStreamReader(file);
            Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();

            Employee temp_employee = gson.fromJson(reader, Employee.class);
            if (temp_employee != null) {
                temp_employeesArray[i] = temp_employee;
                System.out.println("Loaded file " + listOfFiles[i].getName());
                empIdx++;//  w  w w.ja  v  a2s  .co  m
            } else {
                try {
                    throw new Exception("Json File " + path + listOfFiles[i].getName()
                            + " is an invalid Employee.class json file");
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
    Employee[] employeesArray = new Employee[empIdx];
    int empIdx2 = 0;
    for (Employee e : temp_employeesArray) {
        if (e != null) {
            employeesArray[empIdx2] = e;
            empIdx2++;
        }
    }
    return employeesArray;
}

From source file:ca.travelagency.utils.JsonUtils.java

License:Apache License

public JsonUtils() {
    gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateSerializer())
            .registerTypeAdapter(Date.class, new DateDeserializer())
            .registerTypeAdapter(byte[].class, new ByteArraySerializer())
            .registerTypeAdapter(byte[].class, new ByteArrayDeserializer()).create();
}