Example usage for com.google.gson.stream JsonReader JsonReader

List of usage examples for com.google.gson.stream JsonReader JsonReader

Introduction

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

Prototype

public JsonReader(Reader in) 

Source Link

Document

Creates a new instance that reads a JSON-encoded stream from in .

Usage

From source file:io.teamelite.menu_controller.system.file.ItemHandler.java

License:Open Source License

/**
 * Loads the list with items generated from their respective file files
 *///from   w w  w. j a v  a  2 s. c  o  m
private void load() {
    Gson g = GsonFactory.getPrettyGson();
    File dir = MenuController.getPlugin().getItemDirectory();
    if (dir != null && dir.exists() && dir.listFiles().length > 0) {
        for (File f : dir.listFiles()) {
            try {
                JsonReader content = new JsonReader(new FileReader(f));
                JsonParser parser = new JsonParser();
                JsonElement e = parser.parse(content);
                if (e.isJsonObject()) {
                    JsonObject o = e.getAsJsonObject();
                    if (o.has("class") && o.has("menu_item")) {
                        if (o.get("class").getAsString() != null) {
                            Class c = null;
                            try {
                                c = Class.forName(o.get("class").getAsString());
                                this.items.add(
                                        GsonFactory.getPrettyGson().<MenuItem>fromJson(o.get("menu_item"), c));
                            } catch (ClassNotFoundException ex) {
                                Bukkit.getLogger().log(Level.INFO,
                                        "Unable to retrieve the class: " + String.valueOf(o.get("class")));
                            }
                        }
                    }
                }
            } catch (FileNotFoundException e) {
                Bukkit.getLogger().log(Level.INFO, "Unable to retrieve JSON from " + f.getName() + ".");
            }
        }
    }
}

From source file:it.bradipao.berengar.DbTool.java

License:Apache License

public static int gson2db(SQLiteDatabase mDB, File jsonFile) {

    // vars//from w w w.j  av  a2 s.c  o m
    int iTableNum = 0;
    FileReader fr = null;
    BufferedReader br = null;
    JsonReader jr = null;
    String name = null;
    String val = null;

    String mTable = null;
    String mTableSql = null;
    ArrayList<String> aFields = null;
    ArrayList<String> aValues = null;
    ContentValues cv = null;

    // file readers
    try {
        fr = new FileReader(jsonFile);
        br = new BufferedReader(fr);
        jr = new JsonReader(br);
    } catch (FileNotFoundException e) {
        Log.e(LOGTAG, "error in gson2db file readers", e);
    }

    // parsing
    try {
        // start database transaction
        mDB.beginTransaction();
        // open root {
        jr.beginObject();
        // iterate through root objects
        while (jr.hasNext()) {
            name = jr.nextName();
            if (jr.peek() == JsonToken.NULL)
                jr.skipValue();
            // number of tables
            else if (name.equals("tables_num")) {
                val = jr.nextString();
                iTableNum = Integer.parseInt(val);
                if (GOLOG)
                    Log.d(LOGTAG, "TABLE NUM : " + iTableNum);
            }
            // iterate through tables array
            else if (name.equals("tables")) {
                jr.beginArray();
                while (jr.hasNext()) {
                    // start table
                    mTable = null;
                    aFields = null;
                    jr.beginObject();
                    while (jr.hasNext()) {
                        name = jr.nextName();
                        if (jr.peek() == JsonToken.NULL)
                            jr.skipValue();
                        // table name
                        else if (name.equals("table_name")) {
                            mTable = jr.nextString();
                        }
                        // table sql
                        else if (name.equals("table_sql")) {
                            mTableSql = jr.nextString();
                            if ((mTable != null) && (mTableSql != null)) {
                                mDB.execSQL("DROP TABLE IF EXISTS " + mTable);
                                mDB.execSQL(mTableSql);
                                if (GOLOG)
                                    Log.d(LOGTAG, "DROPPED AND CREATED TABLE : " + mTable);
                            }
                        }
                        // iterate through columns name
                        else if (name.equals("cols_name")) {
                            jr.beginArray();
                            while (jr.hasNext()) {
                                val = jr.nextString();
                                if (aFields == null)
                                    aFields = new ArrayList<String>();
                                aFields.add(val);
                            }
                            jr.endArray();
                            if (GOLOG)
                                Log.d(LOGTAG, "COLUMN NAME : " + aFields.toString());
                        }
                        // iterate through rows
                        else if (name.equals("rows")) {
                            jr.beginArray();
                            while (jr.hasNext()) {
                                jr.beginArray();
                                // iterate through values in row
                                aValues = null;
                                cv = null;
                                while (jr.hasNext()) {
                                    val = jr.nextString();
                                    if (aValues == null)
                                        aValues = new ArrayList<String>();
                                    aValues.add(val);
                                }
                                jr.endArray();
                                // add to database
                                cv = new ContentValues();
                                for (int j = 0; j < aFields.size(); j++)
                                    cv.put(aFields.get(j), aValues.get(j));
                                mDB.insert(mTable, null, cv);
                                if (GOLOG)
                                    Log.d(LOGTAG, "INSERT IN " + mTable + " : " + aValues.toString());
                            }
                            jr.endArray();
                        } else
                            jr.skipValue();
                    }
                    // end table
                    jr.endObject();
                }
                jr.endArray();
            } else
                jr.skipValue();
        }
        // close root }
        jr.endObject();
        jr.close();
        // successfull transaction
        mDB.setTransactionSuccessful();
    } catch (IOException e) {
        Log.e(LOGTAG, "error in gson2db gson parsing", e);
    } finally {
        mDB.endTransaction();
    }

    return iTableNum;
}

From source file:it.polimi.modaclouds.monitoring.monitoring_manager.server.ActionsExecutorServer.java

License:Apache License

static List<MonitoringDatum> jsonToMonitoringDatum(String json) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(json));
    Type type = new TypeToken<Map<String, Map<String, List<Map<String, String>>>>>() {
    }.getType();/*w  w w  .j  av a  2  s .  c om*/
    Map<String, Map<String, List<Map<String, String>>>> jsonMonitoringData = new Gson().fromJson(reader, type);
    List<MonitoringDatum> monitoringData = new ArrayList<MonitoringDatum>();
    if (jsonMonitoringData.isEmpty()) {
        return monitoringData;
    }
    for (Map<String, List<Map<String, String>>> jsonMonitoringDatum : jsonMonitoringData.values()) {
        MonitoringDatum datum = new MonitoringDatum();
        datum.setMetric(nullable(jsonMonitoringDatum.get(DDAOntology.metric.toString())).get(0).get("value"));
        datum.setTimestamp(
                nullable(jsonMonitoringDatum.get(DDAOntology.timestamp.toString())).get(0).get("value"));
        datum.setValue(nullable(jsonMonitoringDatum.get(DDAOntology.value.toString())).get(0).get("value"));
        datum.setResourceId(
                nullable(jsonMonitoringDatum.get(DDAOntology.resourceId.toString())).get(0).get("value"));
        monitoringData.add(datum);
    }
    return monitoringData;
}

From source file:it.smartcommunitylab.JSON.java

License:Apache License

/**
 * Deserialize the given JSON string to Java object.
 *
 * @param <T>        Type//from  w  ww . j  a v a2  s .co  m
 * @param body       The JSON string
 * @param returnType The type to deserialize into
 * @return The deserialized Java object
 */
@SuppressWarnings("unchecked")
public <T> T deserialize(String body, Type returnType) {
    try {
        if (isLenientOnJson) {
            JsonReader jsonReader = new JsonReader(new StringReader(body));
            // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
            jsonReader.setLenient(true);
            return gson.fromJson(jsonReader, returnType);
        } else {
            return gson.fromJson(body, returnType);
        }
    } catch (JsonParseException e) {
        // Fallback processing when failed to parse JSON form response body:
        // return the response body string directly for the String return type;
        if (returnType.equals(String.class))
            return (T) body;
        else
            throw (e);
    }
}

From source file:jsondiscoverer.JsonSource.java

License:Open Source License

/**
 * Builds a {@link JsonData} element out of a JSON document representing the input and another
 * JSON document representing the output. 
 * <p>/*from   www  .  j a  va  2s.  c  o  m*/
 * The input/output must be provided as a valid JSON objects.
 * 
 * @param input The {@link Reader} from which obtain JSON document used as input (optional)
 * @param output The {@link Reader} from which obtain the JSON document
 * @throws IllegalArgumentException If any reader is null 
 * @return The {@link JsonData} with the JSON document and the input
 */
private JsonData buildJsonData(Reader input, Reader output) {
    if (output == null)
        throw new IllegalArgumentException("The JSON document cannot be null and must exist");

    JsonObject inputJsonObject = null;
    if (input != null) {
        JsonElement inputElement = (new JsonParser()).parse(new JsonReader(input));
        if (!inputElement.isJsonObject())
            throw new JsonParseException("The input value must be a valid JSON object. Received " + input);
        inputJsonObject = inputElement.getAsJsonObject();
    }

    JsonElement rootElement = (new JsonParser()).parse(new JsonReader(output));
    JsonData data = new JsonData(inputJsonObject, rootElement);
    return data;
}

From source file:json_export_import.GSON_Observer.java

public void read() {
    try {//  w w w .  ja  v a 2 s  .  c  o  m
        JsonReader reader = new JsonReader(new FileReader("/home/rgreim/Output.json"));
        reader.beginArray();
        while (reader.hasNext()) {
            String sequence = reader.nextString();
            System.out.println("Sequenz: " + sequence);
        }
        reader.endArray();
        reader.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GSON_Observer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GSON_Observer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:kihira.minicreatures.MiniCreatures.java

License:Open Source License

@SuppressWarnings("ResultOfMethodCallIgnored")
private void loadPersonalityTypes(File configDir) {
    File personalityTypesFile = new File(configDir,
            File.separator + "MiniCreatures" + File.separator + "PersonalityTypes.json");

    try {//from   w w w  . j a v a  2  s.c om
        Gson gson = GsonHelper.createGson(Mood.class);
        if (!personalityTypesFile.exists()) {
            //Create files/directories
            new File(configDir, File.separator + "MiniCreatures").mkdirs();
            personalityTypesFile.createNewFile();

            JsonWriter jsonWriter = new JsonWriter(new FileWriter(personalityTypesFile));

            //TODO just copy a pre-genned file like marker beacons
            //Create defaults
            //Create default personalities
            jsonWriter.beginArray();
            List<String> list = new ArrayList<String>();
            list.add(EntityMiniPlayer.class.getName());
            gson.toJson(gson.toJsonTree(new Mood("psychotic", list, new HashMap<String, MoodVariable>() {
                {
                    put("happiness", new MoodVariable(35, 50));
                    put("hostility", new MoodVariable(40, 50));
                }
            })), jsonWriter);
            gson.toJson(gson.toJsonTree(new Mood("coldblooded", list, new HashMap<String, MoodVariable>() {
                {
                    put("happiness", new MoodVariable(-50, 0));
                    put("hostility", new MoodVariable(40, 50));
                }
            })), jsonWriter);
            gson.toJson(gson.toJsonTree(new Mood("happy", list, new HashMap<String, MoodVariable>() {
                {
                    put("happiness", new MoodVariable(10, 50));
                    put("hostility", new MoodVariable(-50, 10));
                }
            })), jsonWriter);
            gson.toJson(gson.toJsonTree(new Mood("depressed", list, new HashMap<String, MoodVariable>() {
                {
                    put("happiness", new MoodVariable(-50, 0));
                    put("hostility", new MoodVariable(-10, 10));
                }
            })), jsonWriter);
            gson.toJson(gson.toJsonTree(new MoodTest("test")), jsonWriter);
            jsonWriter.endArray();
            jsonWriter.close();
        }

        //Load personality types
        JsonReader reader = new JsonReader(new FileReader(personalityTypesFile));
        reader.beginArray();
        while (reader.hasNext()) {
            Mood mood = gson.fromJson(reader, Mood.class);
            Personality.moodList.add(mood);
            logger.debug("Loaded mood %s", mood.toString());
        }
        reader.endArray();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}

From source file:koodikoe.database.ConfigReader.java

public static final Credentials getCredentials() {
    Gson g = new Gson();
    InputStream is = ConfigReader.class.getResourceAsStream("/dbConfig.json");
    if (is == null) {
        return new Credentials("test", "bar");
    }/*from   w w  w.  j  a  v  a 2  s  .co m*/
    JsonReader reader = new JsonReader(new InputStreamReader(is));
    Credentials creds = g.fromJson(reader, Credentials.class);
    return creds;
}

From source file:kriswuollett.sandbox.twitter.api.streaming.gson.GsonTwitterStreamingRequest.java

License:Open Source License

@Override
public TwitterStreamingResponse call() throws Exception {
    if (listener == null)
        throw new IllegalStateException("The listener was null");

    final InputStream in;

    if (inputStream == null) {
        if (consumer == null)
            throw new IllegalStateException("The consumer was null");

        if (track == null)
            throw new IllegalStateException("The track was null");

        final HttpPost post = new HttpPost("https://stream.twitter.com/1/statuses/filter.json");

        final List<NameValuePair> nvps = new LinkedList<NameValuePair>();

        // nvps.add( new BasicNameValuePair( "track", "twitter" ) );
        // nvps.add( new BasicNameValuePair( "locations", "-74,40,-73,41" ) );
        //nvps.add( new BasicNameValuePair( "track", "'nyc','ny','new york','new york city'" ) );
        nvps.add(new BasicNameValuePair("track", track));
        post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

        consumer.sign(post);//from w w w  .  j  a v a 2  s.c  om

        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpResponse response = httpClient.execute(post);

        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK)
            return new Response(false, response.getStatusLine().getReasonPhrase());

        in = response.getEntity().getContent();
    } else {
        if (consumer != null)
            throw new IllegalStateException("The consumer parameter cannot be used with inputStream");

        if (track != null)
            throw new IllegalStateException("The track parameter cannot be used with inputStream");

        in = inputStream;
    }

    reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
    reader.setLenient(true);

    try {
        stack1.clear();

        ParseState state = new ParseState(State.BEGIN, null, null);

        stack1.push(state);

        while (true) {
            final JsonToken token = reader.peek();

            switch (token) {
            case BEGIN_ARRAY:
                reader.beginArray();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sBEGIN_ARRAY STATE=%s STACK_SIZE=%d", padding(stack1.size()),
                            state, stack1.size()));
                onBeginArray();
                break;
            case END_ARRAY:
                reader.endArray();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sEND_ARRAY STATE=%s STACK_SIZE=%d", padding(stack1.size()),
                            state, stack1.size()));
                onEndArray();
                break;
            case BEGIN_OBJECT:
                reader.beginObject();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sBEGIN_OBJECT STATE=%s STACK_SIZE=%d", padding(stack1.size()),
                            state, stack1.size()));
                onBeginObject();
                break;
            case END_OBJECT:
                reader.endObject();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sEND_OBJECT STATE=%s STACK_SIZE=%d", padding(stack1.size()),
                            state, stack1.size()));
                onEndObject();
                break;
            case NAME:
                String name = reader.nextName();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sNAME - %s", padding(stack1.size()), name));
                onName(name);
                break;
            case STRING:
                String s = reader.nextString();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sSTRING - %s", padding(stack1.size()), s));
                onString(s);
                break;
            case NUMBER:
                String n = reader.nextString();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sNUMBER - %s", padding(stack1.size()), n));
                onNumber(n);
                break;
            case BOOLEAN:
                boolean b = reader.nextBoolean();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sBOOLEAN - %b", padding(stack1.size()), b));
                onBoolean(b);
                break;
            case NULL:
                reader.nextNull();
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sNULL", padding(stack1.size())));
                onNull();
                break;
            case END_DOCUMENT:
                if (log.isLoggable(Level.FINEST))
                    log.finest(String.format("%sEND_DOCUMENT", padding(stack1.size())));
                return new Response(true, "OK");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:little.nj.mprisdroid.ClientFragment.java

License:Open Source License

/**
 * Start the listener thread for server responses
 *///from   ww w .  j  a va 2 s.  c  om
public void startListening() {
    Log.d(TAG, "ClientFragment: startListening");

    m_thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                JsonReader reader = new JsonReader(new InputStreamReader(m_is));
                reader.setLenient(true);

                do {
                    final ServerResponse resp = m_gson.fromJson(reader, ServerResponse.class);

                    handleResponse(resp);

                } while (!Thread.interrupted());
            } catch (Exception ie) {
                if (!disconnecting)
                    Log.e(TAG, "ClientFragment: Exception while Listening", ie);

                signalDisconnect();
            }
        }
    });

    m_thread.start();
}