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

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

Introduction

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

Prototype

public boolean hasNext() throws IOException 

Source Link

Document

Returns true if the current array or object has another element.

Usage

From source file:com.google.maps.internal.DurationAdapter.java

License:Open Source License

/**
 * Read a distance object from a Directions API result and convert it to a {@link Distance}.
 *
 * <p>We are expecting to receive something akin to the following:
 * <pre>/* w w  w  . j a  v  a2  s . co m*/
 * {
 *   "value": 207,
     "text": "0.1 mi"
 * }
 * </pre>
 */
@Override
public Duration read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();
        return null;
    }

    Duration duration = new Duration();

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("text")) {
            duration.humanReadable = reader.nextString();
        } else if (name.equals("value")) {
            duration.inSeconds = reader.nextLong();
        }

    }
    reader.endObject();

    return duration;
}

From source file:com.google.maps.internal.FareAdapter.java

License:Open Source License

/**
 * Read a Fare object from the Directions API and convert to a {@link com.google.maps.model.Fare}
 *
 * <pre>{//w ww  .j  a v  a 2 s  .c  om
 *   "currency": "USD",
 *   "value": 6
 * }</pre>
 */
@Override
public Fare read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();
        return null;
    }

    Fare fare = new Fare();
    reader.beginObject();
    while (reader.hasNext()) {
        String key = reader.nextName();
        if ("currency".equals(key)) {
            fare.currency = Currency.getInstance(reader.nextString());
        } else if ("value".equals(key)) {
            // this relies on nextString() being able to coerce raw numbers to strings
            fare.value = new BigDecimal(reader.nextString());
        } else {
            // Be forgiving of unexpected values
            reader.skipValue();
        }
    }
    reader.endObject();

    return fare;
}

From source file:com.google.maps.internal.GeolocationResponseAdapter.java

License:Open Source License

@Override
public GeolocationApi.Response read(JsonReader reader) throws IOException {

    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();//from  w  w  w . j a  va  2 s.  com
        return null;
    }
    GeolocationApi.Response response = new GeolocationApi.Response();
    LatLngAdapter latLngAdapter = new LatLngAdapter();

    reader.beginObject(); // opening {
    while (reader.hasNext()) {
        String name = reader.nextName();
        // two different objects could be returned a success object containing "location" and "accuracy"
        // keys or an error object containing an "error" key
        if (name.equals("location")) {
            // we already have a parser for the LatLng object so lets use that
            response.location = latLngAdapter.read(reader);
        } else if (name.equals("accuracy")) {
            response.accuracy = reader.nextDouble();
        } else if (name.equals("error")) {
            reader.beginObject(); // the error key leads to another object...
            while (reader.hasNext()) {
                String errName = reader.nextName();
                // ...with keys "errors", "code" and "message"
                if (errName.equals("code")) {
                    response.code = reader.nextInt();
                } else if (errName.equals("message")) {
                    response.message = reader.nextString();
                } else if (errName.equals("errors")) {
                    reader.beginArray(); // its plural because its an array of errors...
                    while (reader.hasNext()) {
                        reader.beginObject();// ...and each error array element is an object...
                        while (reader.hasNext()) {
                            errName = reader.nextName();
                            // ...with keys "reason", "domain", "debugInfo", "location", "locationType",  and "message" (again)
                            if (errName.equals("reason")) {
                                response.reason = reader.nextString();
                            } else if (errName.equals("domain")) {
                                response.domain = reader.nextString();
                            } else if (errName.equals("debugInfo")) {
                                response.debugInfo = reader.nextString();
                            } else if (errName.equals("message")) {
                                // have this already
                                reader.nextString();
                            } else if (errName.equals("location")) {
                                reader.nextString();
                            } else if (errName.equals("locationType")) {
                                reader.nextString();
                            }
                        }
                        reader.endObject();
                    }
                    reader.endArray();
                }
            }
            reader.endObject(); // closing }
        }
    }
    reader.endObject();
    return response;
}

From source file:com.google.maps.internal.LatLngAdapter.java

License:Open Source License

/**
 * Reads in a JSON object and try to create a LatLng in one of the following formats.
 *
 * <pre>{/* w w  w. j  a va2  s  . c om*/
 *   "lat" : -33.8353684,
 *   "lng" : 140.8527069
 * }
 *
 * {
 *   "latitude": -33.865257570508334,
 *   "longitude": 151.19287000481452
 * }</pre>
 */
@Override
public LatLng read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();
        return null;
    }

    double lat = 0;
    double lng = 0;
    boolean hasLat = false;
    boolean hasLng = false;

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if ("lat".equals(name) || "latitude".equals(name)) {
            lat = reader.nextDouble();
            hasLat = true;
        } else if ("lng".equals(name) || "longitude".equals(name)) {
            lng = reader.nextDouble();
            hasLng = true;
        }
    }
    reader.endObject();

    if (hasLat && hasLng) {
        return new LatLng(lat, lng);
    } else {
        return null;
    }
}

From source file:com.google.samples.apps.iosched.sync.ConferenceDataHandler.java

License:Open Source License

/**
 * Processes a conference data body and calls the appropriate data type handlers
 * to process each of the objects represented therein.
 *
 * @param dataBody The body of data to process
 * @throws IOException If there is an error parsing the data.
 *///from w  w w . j a va 2  s  .c om
private void processDataBody(String dataBody) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(dataBody));
    JsonParser parser = new JsonParser();
    try {
        reader.setLenient(true); // To err is human

        // the whole file is a single JSON object
        reader.beginObject();

        while (reader.hasNext()) {
            // the key is "rooms", "speakers", "tracks", etc.
            String key = reader.nextName();
            if (mHandlerForKey.containsKey(key)) {
                // pass the value to the corresponding handler
                mHandlerForKey.get(key).process(parser.parse(reader));
            } else {
                LOGW(TAG, "Skipping unknown key in conference data json: " + key);
                reader.skipValue();
            }
        }
        reader.endObject();
    } finally {
        reader.close();
    }
}

From source file:com.google.samples.apps.iosched.sync.userdata.util.UserActionHelper.java

License:Open Source License

public static List<UserAction> deserializeUserActions(String str) {
    try {//from www  .  ja  v a2  s. co  m
        ArrayList<UserAction> actions = new ArrayList<UserAction>();
        JsonReader reader = new JsonReader(new StringReader(str));
        reader.beginArray();
        while (reader.hasNext()) {
            reader.beginObject();
            UserAction action = new UserAction();
            while (reader.hasNext()) {
                String key = reader.nextName();
                if ("type".equals(key)) {
                    action.type = UserAction.TYPE.valueOf(reader.nextString());
                } else if ("id".equals(key)) {
                    action.sessionId = reader.nextString();
                } else {
                    throw new RuntimeException("Invalid key " + key + " in serialized UserAction: " + str);
                }
            }
            reader.endObject();
            actions.add(action);
        }
        reader.endArray();
        return actions;
    } catch (IOException ex) {
        throw new RuntimeException("Error deserializing UserActions: " + str, ex);
    }
}

From source file:com.google.samples.apps.iosched.sync.userdata.util.UserDataHelper.java

License:Open Source License

static public Set<String> fromString(String str) {
    TreeSet<String> result = new TreeSet<String>();
    if (str == null || str.isEmpty()) {
        return result;
    }/* w w  w .  j  a  v a  2s .  c o  m*/
    try {
        JsonReader reader = new JsonReader(new StringReader(str));
        reader.beginObject();
        while (reader.hasNext()) {
            String key = reader.nextName();
            if (JSON_STARRED_SESSIONS_KEY.equals(key)) {
                reader.beginArray();
                while (reader.hasNext()) {
                    result.add(reader.nextString());
                }
                reader.endArray();
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
        reader.close();
    } catch (Exception ex) {
        Log.w(TAG, "Ignoring invalid remote content.", ex);
        return null;
    }
    return result;
}

From source file:com.greensopinion.finance.services.persistence.CategoriesTypeAdapter.java

License:Apache License

@Override
public Categories read(JsonReader reader) throws IOException {
    reader.beginObject();//from   www  . ja va  2  s.  com
    checkState(NAME_CATEGORIES.equals(reader.nextName()));
    reader.beginArray();

    ImmutableList.Builder<Category> elements = ImmutableList.<Category>builder();
    while (reader.hasNext()) {
        if (reader.peek() == JsonToken.BEGIN_OBJECT) {
            elements.add(gson.getAdapter(Category.class).read(reader));
        } else {
            elements.add(readCategory(reader.nextString()));
        }
    }
    reader.endArray();
    reader.endObject();

    return new Categories(elements.build());
}

From source file:com.greensopinion.finance.services.persistence.TransactionsTypeAdapter.java

License:Apache License

@Override
public Transactions read(JsonReader reader) throws IOException {
    reader.beginObject();/*w  w w .ja v a 2s. c o  m*/
    checkState(reader.nextName().equals(NAME_TRANSACTIONS));
    reader.beginArray();

    ImmutableList.Builder<Transaction> elements = ImmutableList.builder();
    while (reader.hasNext()) {
        elements.add(readTransaction(reader.nextString()));
    }

    reader.endArray();
    reader.endObject();
    return new Transactions(elements.build());
}

From source file:com.hichinaschool.flashcards.async.DeckTask.java

License:Open Source License

private TaskData doInBackgroundImportReplace(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundImportReplace");
    Collection col = params[0].getCollection();
    String path = params[0].getString();
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();

    // extract the deck from the zip file
    String fileDir = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpzip";
    File dir = new File(fileDir);
    if (dir.exists()) {
        BackupManager.removeDir(dir);/*from   www .j a v  a  2 s.c  o  m*/
    }

    publishProgress(new TaskData(res.getString(R.string.import_unpacking)));
    // from anki2.py
    String colFile = fileDir + "/collection.anki2";
    ZipFile zip;
    try {
        zip = new ZipFile(new File(path), ZipFile.OPEN_READ);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - Error while unzipping: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace0");
        return new TaskData(false);
    }
    if (!Utils.unzipFiles(zip, fileDir, new String[] { "collection.anki2", "media" }, null)
            || !(new File(colFile)).exists()) {
        return new TaskData(-2, null, false);
    }

    Collection tmpCol = null;
    try {
        tmpCol = Storage.Collection(colFile);
        if (!tmpCol.validCollection()) {
            tmpCol.close();
            return new TaskData(-2, null, false);
        }
    } finally {
        if (tmpCol != null) {
            tmpCol.close();
        }
    }

    publishProgress(new TaskData(res.getString(R.string.importing_collection)));
    String colPath;
    if (col != null) {
        // unload collection and trigger a backup
        colPath = col.getPath();
        AnkiDroidApp.closeCollection(true);
        BackupManager.performBackup(colPath, true);
    }
    // overwrite collection
    colPath = AnkiDroidApp.getCollectionPath();
    File f = new File(colFile);
    f.renameTo(new File(colPath));
    int addedCount = -1;
    try {
        col = AnkiDroidApp.openCollection(colPath);

        // because users don't have a backup of media, it's safer to import new
        // data and rely on them running a media db check to get rid of any
        // unwanted media. in the future we might also want to duplicate this step
        // import media
        HashMap<String, String> nameToNum = new HashMap<String, String>();
        HashMap<String, String> numToName = new HashMap<String, String>();
        File mediaMapFile = new File(fileDir, "media");
        if (mediaMapFile.exists()) {
            JsonReader jr = new JsonReader(new FileReader(mediaMapFile));
            jr.beginObject();
            String name;
            String num;
            while (jr.hasNext()) {
                num = jr.nextName();
                name = jr.nextString();
                nameToNum.put(name, num);
                numToName.put(num, name);
            }
            jr.endObject();
            jr.close();
        }
        String mediaDir = col.getMedia().getDir();
        int total = nameToNum.size();
        int i = 0;
        for (Map.Entry<String, String> entry : nameToNum.entrySet()) {
            String file = entry.getKey();
            String c = entry.getValue();
            File of = new File(mediaDir, file);
            if (!of.exists()) {
                Utils.unzipFiles(zip, mediaDir, new String[] { c }, numToName);
            }
            ++i;
            publishProgress(new TaskData(res.getString(R.string.import_media_count, (i + 1) * 100 / total)));
        }
        zip.close();
        // delete tmp dir
        BackupManager.removeDir(dir);

        publishProgress(new TaskData(res.getString(R.string.import_update_counts)));
        // Update the counts
        DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col));
        if (result == null) {
            return null;
        }
        return new TaskData(addedCount, result.getObjArray(), true);
    } catch (RuntimeException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - RuntimeException: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace1");
        return new TaskData(false);
    } catch (FileNotFoundException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - FileNotFoundException: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace2");
        return new TaskData(false);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - IOException: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace3");
        return new TaskData(false);
    }
}