Example usage for com.google.gson Gson toJson

List of usage examples for com.google.gson Gson toJson

Introduction

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

Prototype

public void toJson(JsonElement jsonElement, JsonWriter writer) throws JsonIOException 

Source Link

Document

Writes the JSON for jsonElement to writer .

Usage

From source file:RunnerRepository.java

License:Apache License

public static void writeJSon() {
    try {//from  ww  w .ja  v a 2 s.  c o  m
        Writer writer = new OutputStreamWriter(new FileOutputStream(TWISTERINI));
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        gson.toJson(inifile, writer);
        writer.close();
    } catch (Exception e) {
        System.out.println("Could not write to local config file");
        e.printStackTrace();
    }
}

From source file:actforothers.VolunteerDB.java

String importDrivers(JFrame pFrame, Date today, String user, ImageIcon oncIcon) {
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Select Volunteer .csv file to import");
    chooser.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv"));

    int volunteersAddedCount = 0;
    File volFile = null;//from  w  w w .ja  va  2 s .c om

    int returnVal = chooser.showOpenDialog(pFrame);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        volFile = chooser.getSelectedFile();
        CSVReader reader = null;
        try {
            reader = new CSVReader(new FileReader(volFile.getAbsoluteFile()));
            String[] nextLine, header;

            if ((header = reader.readNext()) != null) {
                //Read the ONC CSV File
                if (header.length == DRIVER_CSVFILE_HEADER_LENGTH) {
                    //build a list of ONCVolunteers from the file.
                    List<ONCVolunteer> volList = new ArrayList<ONCVolunteer>();

                    while ((nextLine = reader.readNext()) != null) // nextLine[] is an array of values from the line
                    {
                        //don't process records that don't have at least a first or last name
                        if (nextLine.length > 8 && nextLine[6].length() + nextLine[7].length() > 2) {
                            //                         System.out.println(String.format("fn %s ln %s", nextLine[6], nextLine[7]));
                            ONCVolunteer currVol = searchVolunteerListForMatch(nextLine[6], nextLine[7],
                                    volList);

                            if (currVol != null) {
                                //update the volunteer with the activity from this line
                                currVol.setActivityCode(
                                        updateActivityCode(nextLine[4], currVol.getActivityCode()));
                            } else {
                                //create a new volunteer and add it
                                int newActivityCode = updateActivityCode(nextLine[4], 0);
                                ONCVolunteer newVol = new ONCVolunteer(nextLine, today, user, newActivityCode);

                                volList.add(newVol);
                            }
                        }
                    }

                    Collections.sort(volList);

                    //now that we have a list of volunteers from the file, send the to the
                    //server to add to the existing database
                    //create the request to the server to import the families
                    Gson gson = new Gson();
                    Type listtype = new TypeToken<ArrayList<ONCVolunteer>>() {
                    }.getType();

                    String response = serverIF
                            .sendRequest("POST<volunteer_group>" + gson.toJson(volList, listtype));

                    if (response != null && response.startsWith("ADDED_VOLUNTEER_GROUP")) {
                        //process the list of jsons returned, adding agent, families, adults
                        //and children to the local databases
                        Type jsonlisttype = new TypeToken<ArrayList<String>>() {
                        }.getType();
                        ArrayList<String> changeList = gson.fromJson(response.substring(21), jsonlisttype);

                        //loop thru list of changes, processing each one
                        for (String change : changeList)
                            if (change.startsWith("ADDED_DRIVER")) {
                                this.processAddedObject(this, change.substring("ADDED_DRIVER".length()));
                                volunteersAddedCount++;
                            }
                    } else {
                        JOptionPane.showMessageDialog(pFrame,
                                "An error occured, " + volFile.getName() + " cannot be imported by the server",
                                "ONC Server Britepath Import Error", JOptionPane.ERROR_MESSAGE,
                                GlobalVariables.getONCLogo());
                    }
                } else
                    JOptionPane.showMessageDialog(pFrame,
                            "Volunteer file corrupted, header length = " + Integer.toString(header.length),
                            "Invalid Volunteer File", JOptionPane.ERROR_MESSAGE, oncIcon);
            } else
                JOptionPane.showMessageDialog(pFrame, "Couldn't read header in file: " + volFile.getName(),
                        "Invalid Volunteer File", JOptionPane.ERROR_MESSAGE, oncIcon);
        } catch (IOException x) {
            JOptionPane.showMessageDialog(pFrame, "Unable to open Volunteer file: " + volFile.getName(),
                    "Volunteer file not found", JOptionPane.ERROR_MESSAGE, oncIcon);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    //If no drivers were in the file
    if (volFile == null || volunteersAddedCount == 0)
        return "No Delivery Drivers were imported";
    else
        return String.format("%d Delivery Drivers imported from %s", volunteersAddedCount, volFile.getName());

}

From source file:actforothers.VolunteerDB.java

String add(Object source, ONCObject entity) {
    Gson gson = new Gson();
    String response = "";

    response = serverIF.sendRequest("POST<add_driver>" + gson.toJson(entity, ONCVolunteer.class));

    if (response.startsWith("ADDED_DRIVER"))
        processAddedObject(source, response.substring(12));

    return response;
}

From source file:actforothers.VolunteerDB.java

@Override
String update(Object source, ONCObject entity) {
    Gson gson = new Gson();
    String response = "";

    response = serverIF.sendRequest("POST<update_driver>" + gson.toJson(entity, ONCVolunteer.class));

    if (response.startsWith("UPDATED_DRIVER")) {
        processUpdatedObject(source, response.substring(14), volunteerList);
    }//from w w  w  .j a v  a  2  s. c o  m

    return response;
}

From source file:actforothers.VolunteerDB.java

String delete(Object source, ONCObject entity) {
    Gson gson = new Gson();
    String response = "";

    response = serverIF.sendRequest("POST<delete_driver>" + gson.toJson(entity, ONCVolunteer.class));

    if (response.startsWith("DELETED_DRIVER"))
        processDeletedObject(source, response.substring(14));

    return response;
}

From source file:app.philm.in.tasks.FetchTmdbConfigurationRunnable.java

License:Apache License

private void writeConfigToFile(TmdbConfiguration configuration) {
    FileWriter writer = null;/*from   w  w w . j  a  v  a 2s  .  c om*/

    try {
        File file = mFileManager.getFile(FILENAME_TMDB_CONFIG);
        if (!file.exists()) {
            file.createNewFile();
        }

        writer = new FileWriter(file, false);
        Gson gson = new Gson();
        gson.toJson(configuration, writer);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:be.uza.keratoconus.systemtrayapp.SystemTrayMenu.java

License:Open Source License

private void writeConfig(UserPrefsDAO userConfig) {
    Gson gson = new Gson();
    Path path = prefsDirPath.resolve(FileSystems.getDefault().getPath(PREFS_FILE_NAME));
    logInfo("Writing JSON to " + path);
    try (final OutputStreamWriter writer = new OutputStreamWriter(Files.newOutputStream(path))) {
        gson.toJson(userConfig, writer);
    } catch (IOException e) {
        logException(e, "Problem encountered when saving user configuration to " + path);
    }//from   ww w. ja  va  2 s.c  o m
}

From source file:blainelewis1.cmput301assignment1.ClaimManager.java

License:Apache License

public void serialize(Context context) {

    //Why write nothing?
    if (this.claims == null) {
        return;//from ww w  . j  a v a 2 s .  c o  m
    }

    Gson gson = new Gson();

    try {

        OutputStreamWriter writer = new OutputStreamWriter(
                context.openFileOutput(saveFileName, Context.MODE_PRIVATE));

        gson.toJson(claims, writer);

        writer.close();

    } catch (IOException e) {
        // Fail silently, we can't do anything about this...
        Log.e("Error", "Serialize failed", e);
    }

}

From source file:br.com.bean.RestControllers.alunoController.java

@RequestMapping(value = "buscaPorId-aluno", method = RequestMethod.GET)
public String get(long id) throws HibernateException {
    Session sessao = HibernateUtility.getSession();
    try {// w w w .  j ava2 s. com
        Aluno a = (Aluno) sessao.get(Aluno.class, id);
        Gson gson = new Gson();
        return gson.toJson(a, Aluno.class);
    } catch (HibernateException e) {
        return CriadorJson.criaJsonErro(e, "Verificar");
    } finally {
        sessao.close();
    }
}

From source file:br.com.bean.RestControllers.alunoController.java

@RequestMapping(value = "busca-alunos", method = RequestMethod.GET)
public String get() throws ParseException {
    Session sessao = HibernateUtility.getSession();
    Transaction transacao = sessao.beginTransaction();
    try {//from w  ww .  j  ava  2s  . c om
        Criteria query = sessao.createCriteria(Aluno.class);
        Criterion ativo = Restrictions.eq("ativo", 1);
        query.add(ativo);
        List<Aluno> listaDeAlunos = query.list();
        Type TipolistaDeAlunos = new TypeToken<List<Aluno>>() {
        }.getType();
        Gson gson = new GsonBuilder().registerTypeAdapter(Collection.class, new CollectionDeserializer())
                .create();
        return gson.toJson(listaDeAlunos, TipolistaDeAlunos);
    } catch (HibernateException e) {
        transacao.rollback();
        return null;
    }
}