Example usage for com.google.gson Gson fromJson

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public <T> T fromJson(JsonElement json, Type typeOfT) throws JsonSyntaxException 

Source Link

Document

This method deserializes the Json read from the specified parse tree into an object of the specified type.

Usage

From source file:ca.cs.ualberta.localpost.view.UserProfile.java

License:Open Source License

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    //super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == OBTAIN_EDIT_COMMENT_CODE) {
        if (resultCode == Activity.RESULT_OK) {
            Gson gson = new Gson();
            String returnObj = data.getStringExtra("returnObj");
            String returnIndex = data.getStringExtra("returnIndex");
            RootCommentModel edited_root = gson.fromJson(returnObj, RootCommentModel.class);

            model.set(Integer.valueOf(returnIndex), edited_root);

            File dir = getFilesDir();
            File file = new File(dir, "rootcomment.json");
            boolean deleted = file.delete();

            for (CommentModel m : model) {
                Serialize.SaveComment(m, UserProfile.this, null);
            }//from   w  ww  .  j a  v  a 2 s. c  om
        }
    }
    if (requestCode == OBTAIN_ADDRESS_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            String intentIndex = data.getStringExtra("address");
            address = gson.fromJson(intentIndex, android.location.Address.class);
            user.setAddress(address);
            Serialize.SaveUser(user, getApplicationContext());
        } else
            super.onActivityResult(requestCode, resultCode, data);
    }
}

From source file:ca.etsmtl.applets.etsmobile.api.SignetBackgroundThread.java

License:Apache License

@SuppressWarnings("unchecked")
public T fetchArray() {
    ArrayList<E> array = new ArrayList<E>();

    try {//  w w w .  ja  v  a2s. c o  m
        final StringBuilder sb = new StringBuilder();
        sb.append(urlStr);
        sb.append("/");
        sb.append(action);

        final Gson gson = new Gson();
        final String bodyParamsString = gson.toJson(bodyParams);

        final URL url = new URL(sb.toString());
        final URLConnection conn = url.openConnection();
        conn.addRequestProperty("Content-Type", "application/json");
        conn.addRequestProperty("charset", "utf-8");

        conn.setDoOutput(true);
        final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(bodyParamsString);
        wr.flush();

        final StringWriter writer = new StringWriter();
        final InputStream in = conn.getInputStream();
        IOUtils.copy(in, writer);
        in.close();
        wr.close();

        final String jsonString = writer.toString();

        final ArrayList<E> objectList = new ArrayList<E>();

        JSONObject jsonObject;
        jsonObject = new JSONObject(jsonString);

        JSONArray jsonRootArray;
        jsonRootArray = jsonObject.getJSONObject("d").getJSONArray(liste);
        android.util.Log.d("JSON", jsonRootArray.toString());
        for (int i = 0; i < jsonRootArray.length(); i++) {
            objectList.add(gson.fromJson(jsonRootArray.getJSONObject(i).toString(), typeOfClass));
        }

        array = objectList;
    } catch (final IOException e) {
        e.printStackTrace();
    } catch (final JSONException e) {
        e.printStackTrace();
    }

    return (T) array;
}

From source file:ca.etsmtl.applets.etsmobile.api.SignetBackgroundThread.java

License:Apache License

@SuppressWarnings("unchecked")
public T fetchObject() {
    T object = null;/*from  w  w  w  .j  ava 2  s .  com*/

    try {
        final StringBuilder sb = new StringBuilder();
        sb.append(urlStr);
        sb.append("/");
        sb.append(action);

        final Gson gson = new Gson();
        final String bodyParamsString = gson.toJson(bodyParams);

        final URL url = new URL(sb.toString());
        final URLConnection conn = url.openConnection();
        conn.addRequestProperty("Content-Type", "application/json; charset=UTF-8");

        conn.setDoOutput(true);
        final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(bodyParamsString);
        wr.flush();

        final StringWriter writer = new StringWriter();
        final InputStream in = conn.getInputStream();
        IOUtils.copy(in, writer);
        in.close();
        wr.close();

        final String jsonString = writer.toString();

        JSONObject jsonObject;
        jsonObject = new JSONObject(jsonString);

        JSONObject jsonRootArray;
        jsonRootArray = jsonObject.getJSONObject("d");
        object = (T) gson.fromJson(jsonRootArray.toString(), typeOfClass);
        android.util.Log.d("JSON", jsonRootArray.toString());
    } catch (final MalformedURLException e) {
        e.printStackTrace();
    } catch (final IOException e) {
        e.printStackTrace();
    } catch (final JSONException e) {
        e.printStackTrace();
    }
    return object;
}

From source file:ca.live.hk12.crescent.server.service.FileService.java

License:Open Source License

public static <T> T readData(String fileLocation, Class<T> dataClass) {
    T t = null;/* w ww .java 2 s.co 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) {
        if (ServerLauncher.DEBUG)
            throw new ServerException("Unable to read file:<br>" + fileLocation);
    }
    return t;
}

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  . j a  v a  2 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.nabdullaualberta.buzzergame.FileManager.java

License:Apache License

protected ArrayList<Long> loadFromFile(SinglePlayer player) {

    ArrayList<Long> reactionTimes = new ArrayList<Long>();
    try {//from w ww .  j  a  v  a2s  .c  o m
        FileInputStream fis = context.openFileInput(FILENAME);
        BufferedReader in = new BufferedReader(new InputStreamReader(fis));
        Gson gson = new Gson();
        Type listType = new TypeToken<ArrayList<Long>>() {
        }.getType();
        reactionTimes = gson.fromJson(in, listType);
        fis.close();
    } catch (FileNotFoundException e) {
        reactionTimes = new ArrayList<Long>();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return reactionTimes;
}

From source file:ca.nabdullaualberta.buzzergame.FileManager.java

License:Apache License

protected ArrayList<MultiPlayer> loadFromFile(MultiPlayer player) {
    ArrayList<MultiPlayer> players = new ArrayList<>();
    try {/*w w w  . j a  v  a  2 s. co  m*/
        FileInputStream fis = context.openFileInput(FILENAME);
        BufferedReader in = new BufferedReader(new InputStreamReader(fis));
        Gson gson = new Gson();
        Type listType = new TypeToken<ArrayList<MultiPlayer>>() {
        }.getType();
        players = gson.fromJson(in, listType);
        fis.close();
    } catch (FileNotFoundException e) {
        players = new ArrayList<MultiPlayer>();
        if (player.getNumPlayers() == 2) {
            players.add(0, new MultiPlayer("Player 2"));
            players.add(0, new MultiPlayer("Player 1"));
        } else if (player.getNumPlayers() == 3) {
            players.add(0, new MultiPlayer("Player 3"));
            players.add(0, new MultiPlayer("Player 2"));
            players.add(0, new MultiPlayer("Player 1"));
        } else if (player.getNumPlayers() == 4) {
            players.add(0, new MultiPlayer("Player 4"));
            players.add(0, new MultiPlayer("Player 3"));
            players.add(0, new MultiPlayer("Player 2"));
            players.add(0, new MultiPlayer("Player 1"));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return players;
}

From source file:ca.rossanderson.rhanders_reflex.StatsModel.java

License:Open Source License

private ArrayList<Long> readReactionTimesFromFile(Context cxt) {
    ArrayList<Long> times = null;
    Gson gson = new Gson();
    try {/*from   w w  w  . j a v  a  2s. c  o m*/
        FileInputStream fis = new FileInputStream(getReactionTimesPath(cxt));
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

        Type type = new TypeToken<ArrayList<Long>>() {
        }.getType();
        times = gson.fromJson(reader, type);
        fis.close();
    } catch (FileNotFoundException e) {
        Log.e("Stats", String.format("File not found at '{}'", getReactionTimesPath(cxt)));
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (times == null) {
        times = new ArrayList<Long>();
    }
    return times;
}

From source file:ca.rossanderson.rhanders_reflex.StatsModel.java

License:Open Source License

private HashMap<Integer, HashMap<Integer, Integer>> readGameShowBuzzesFromFile(Context cxt) {
    HashMap<Integer, HashMap<Integer, Integer>> buzzes = null;
    Gson gson = new Gson();
    try {/*from  www. java  2  s.  co m*/
        FileInputStream fis = new FileInputStream(getGameShowPath(cxt));
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

        Type type = new TypeToken<HashMap<Integer, HashMap<Integer, Integer>>>() {
        }.getType();
        buzzes = gson.fromJson(reader, type);
        fis.close();
    } catch (FileNotFoundException e) {
        Log.e("Stats", String.format("File not found at '{}'", getGameShowPath(cxt)));
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (buzzes == null) {
        buzzes = new HashMap<Integer, HashMap<Integer, Integer>>();
    }
    // Fill with zeros: <[2-4], <[1-4], 0>>
    for (int players = 2; players <= 4; players++) {
        for (int playerNum = 1; playerNum <= players; playerNum++) {
            if (buzzes.get(players) == null) {
                buzzes.put(players, new HashMap<Integer, Integer>());
            }
            if (buzzes.get(players).get(playerNum) == null) {
                buzzes.get(players).put(playerNum, 0);
            }
        }
    }
    return buzzes;
}

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  . ja  v  a 2s. c  om*/
        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());

}