Example usage for android.util JsonReader hasNext

List of usage examples for android.util JsonReader hasNext

Introduction

In this page you can find the example usage for android.util 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.workday.autoparse.json.parser.JsonParserUtils.java

/**
 * Parse the next value as an object. If the next value is {@link JsonToken#NULL}, returns
 * null./*  w w w .  ja  v  a2s .c  om*/
 * <p/>
 * This method will use the provide parser, or if none is provided, will attempt find an
 * appropriate parser based on the discrimination value found in the next object. If none is
 * found, then this method returns a {@link JSONObject}.
 *
 * @param reader The JsonReader to use. Calls to {@link JsonReader#beginObject()} and {@link
 * JsonReader#endObject()} will be taken care of by this method.
 * @param parser The parser to use, or null if this method should find an appropriate one on its
 * own.
 * @param key The key corresponding to the current value. This is used to make more useful error
 * messages.
 * @param expectedType The expected class of the resulting object. If the result is not an
 * instance of this class, an exception is thrown.
 *
 * @throws IllegalStateException if the resulting object is not an instance of {@code
 * expectedType}.
 */
public static Object parseJsonObject(JsonReader reader, JsonObjectParser<?> parser, String key,
        Class<?> expectedType) throws IOException, IllegalStateException {
    if (handleNull(reader)) {
        return null;
    }
    assertType(reader, key, JsonToken.BEGIN_OBJECT);

    final String discriminationName = ContextHolder.getContext().getSettings().getDiscriminationName();
    String discriminationValue = null;
    Object result = null;
    reader.beginObject();
    if (parser != null) {
        result = parser.parseJsonObject(null, reader, discriminationName, null);
    } else if (reader.hasNext()) {
        String firstName = reader.nextName();
        final String discriminationKeyName = ContextHolder.getContext().getSettings().getDiscriminationName();
        if (discriminationKeyName.equals(firstName)) {
            discriminationValue = reader.nextString();
            parser = ContextHolder.getContext().getJsonObjectParserTable().get(discriminationValue);
            if (parser != null) {
                result = parser.parseJsonObject(null, reader, discriminationName, discriminationValue);
            } else {
                result = parseSpecificJsonObjectDelayed(reader, discriminationKeyName, discriminationValue);
            }
        } else {
            result = parseSpecificJsonObjectDelayed(reader, firstName, null);
        }

    }
    reader.endObject();

    if (result == null) {
        result = new JSONObject();
    }

    JsonObjectParser<?> unknownObjectParser = ContextHolder.getContext().getSettings().getUnknownObjectParser();
    if (result instanceof JSONObject && unknownObjectParser != null) {
        result = unknownObjectParser.parseJsonObject((JSONObject) result, null, discriminationName,
                discriminationValue);
    }

    if (expectedType != null && !(expectedType.isInstance(result))) {
        throw new IllegalStateException(
                String.format(Locale.US, "Could not convert value at \"%s\" to %s from %s.", key,
                        expectedType.getCanonicalName(), result.getClass().getCanonicalName()));
    }
    return result;
}

From source file:com.workday.autoparse.json.parser.JsonParserUtils.java

/**
 * Parse an array that may have arrays as children into a {@link Collection}.
 *
 * @param reader The reader to use, whose next token should either be {@link JsonToken#NULL} or
 * {@link JsonToken#BEGIN_ARRAY}.//from   w w  w  .  j a  va2  s.  com
 * @param collection The Collection to populate. If nested, the parametrization must match
 * {@code innerCollectionClasses} with the parametrization of the last collection matching
 * {@code itemType}. If not nested, the parametrization should match {@code itemType}.
 * @param itemParser The parser to use for the items of the most deeply nested Collections. May
 * be null.
 * @param itemType The type of the most deeply nested Collections. May not be null, but may be
 * Object.class.
 * @param innerCollectionClasses A flattened list of Collection classes that are nested within
 * {@code collection}. May be null.
 * @param key The key corresponding to the current value. This is used to make more useful error
 * messages.
 */
// Suppress rawtypes and unchecked on Collection and operations. We are depending on
// innerCollectionClasses to
// provide us with the types of all nested collections, and typeClass to be the parameter of
// the deepest
// collection. Assuming these are correct, all other operations are safe.
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> void parseJsonArray(JsonReader reader, Collection collection, JsonObjectParser<T> itemParser,
        Class<T> itemType, List<Class<? extends Collection>> innerCollectionClasses, String key)
        throws IOException {
    if (handleNull(reader)) {
        return;
    }
    assertType(reader, key, JsonToken.BEGIN_ARRAY);

    if (innerCollectionClasses != null && !innerCollectionClasses.isEmpty()) {
        CollectionInitializer nextCollectionInitializer = CollectionInitializerFactory
                .getCollectionInitializerForClass(innerCollectionClasses.get(0));
        reader.beginArray();
        while (reader.hasNext()) {
            Collection nextCollection = nextCollectionInitializer.newInstance();
            parseJsonArray(reader, nextCollection, itemParser, itemType,
                    innerCollectionClasses.subList(1, innerCollectionClasses.size()), key);
            collection.add(nextCollection);
        }
        reader.endArray();
    } else {
        parseFlatJsonArray(reader, collection, itemParser, itemType, key);
    }

}

From source file:br.com.thinkti.android.filechooserfrag.fragFileChooserQuizlet.java

private void getSets(JsonReader reader, List list) throws IOException {
    reader.beginArray();//from   ww w.j  av a  2 s  . c  om
    while (reader.hasNext()) {
        list.add(parseSetJson(reader));
    }
    reader.endArray();
}

From source file:br.com.thinkti.android.filechooserfrag.fragFileChooserQuizlet.java

RowData parseSetJson(JsonReader reader) throws IOException {
    reader.beginObject();//  w w w. j  a  va 2s.c  o  m
    RowData rowData = new RowData();

    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("title")) {
            rowData.name = reader.nextString();
        } else if (name.equals("description")) {
            rowData.description = reader.nextString();
            if (rowData.description.length() > 200)
                rowData.description = rowData.description.substring(0, 100);
        } else if (name.equals("id")) {
            rowData.id = reader.nextInt();
        } else if (name.equals("term_count")) {
            rowData.numCards = reader.nextInt();
        } else if (name.equals("modified_date")) {
            long value = reader.nextLong();
            rowData.lastModified = Data.SHORT_DATE_FORMAT.format(new Date(value * 1000));
            Log.d(Data.APP_ID, " modified_date   value=" + value + " formatted=" + rowData.lastModified
                    + " now=" + (new Date().getTime()));
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
    return rowData;
}

From source file:br.com.thinkti.android.filechooserfrag.fragFileChooserQuizlet.java

typVok parseSetDataJson(JsonReader reader) throws IOException {
    reader.beginObject();/*ww  w .ja va2s . c  o  m*/
    typVok rowData = new typVok();

    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("term")) {
            rowData.Wort = reader.nextString();
        } else if (name.equals("id")) {
            long id = reader.nextLong();
            rowData.z = 0;
        } else if (name.equals("definition")) {
            rowData.Bed1 = reader.nextString();
            rowData.Bed2 = "";
            rowData.Bed3 = "";
        } else if (name.equals("image")) {
            try {
                reader.beginObject();
                while (reader.hasNext()) {
                    String strName = reader.nextName();
                    if (strName.equals("url")) {
                        String value = "<link://" + reader.nextString() + " "
                                + _main.getString(R.string.picture) + "/>";
                        rowData.Kom = value;
                    } else {
                        reader.skipValue();
                    }
                }
                reader.endObject();
            } catch (Exception exception) {
                reader.skipValue();
                //String value = "<link://" + reader.nextString() + "/>";
                //rowData.Kom = value;
            }

        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
    if (lib.libString.IsNullOrEmpty(rowData.Bed1)) {
        rowData.Bed1 = rowData.Kom;
        rowData.Bed2 = "";
        rowData.Bed3 = "";
    }
    return rowData;
}

From source file:br.com.thinkti.android.filechooserfrag.fragFileChooserQuizlet.java

private List<typVok> openSet(String id) throws Exception {
    this.errorDescription = null;
    this.errorTitle = null;
    InputStream inputStream = null;
    List<typVok> list = new ArrayList<typVok>();
    String Kom = "";
    _main.vok.title = "";
    try {//www .  j a v a2 s.c o m
        URL url = new URL(getDeckUrl(id));
        /*
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        if ( connection.getResponseCode() >= 400 ) {
           inputStream = connection.getErrorStream();
        }
        else {
           inputStream = connection.getInputStream();
        }
        */
        inputStream = org.liberty.android.fantastischmemo.downloader.quizlet.lib.makeApiCall(url,
                _main.QuizletAccessToken);
        JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
        reader.beginArray();
        while (reader.hasNext()) {
            reader.beginObject();
            while (reader.hasNext()) {
                String name = reader.nextName();
                if ("id".equals(name)) {
                    long intId = reader.nextLong();
                    /*if (page > totalPages) {
                            
                    }*/
                } else if ("url".equals(name)) {
                    String strUrl = reader.nextString();
                } else if ("title".equals(name)) {
                    String title = reader.nextString();
                    _main.vok.title = title;
                } else if ("created_by".equals(name)) {
                    String created_by = reader.nextString();
                    Kom = _main.getString(R.string.created_by) + " " + created_by + " "
                            + _main.getString((R.string.at)) + " <link://https://quizlet.com/ Quizlet/>";
                } else if ("term_count".equals(name)) {
                    int term_count = reader.nextInt();
                } else if ("lang_terms".equals(name)) {
                    String lang_terms = reader.nextString();
                    try {
                        _LangWord = new Locale(lang_terms.replace("-", "_"));
                    } catch (Throwable ex) {

                    }
                } else if ("lang_definitions".equals(name)) {
                    String lang_definitions = reader.nextString();
                    try {
                        _LangMeaning = (new Locale(lang_definitions.replace("-", "_")));
                    } catch (Throwable ex) {

                    }
                } else if ("terms".equals(name)) {
                    reader.beginArray();
                    while (reader.hasNext()) {
                        typVok v = parseSetDataJson(reader);
                        String kom = v.Kom;
                        v.Kom = Kom;
                        if (!lib.libString.IsNullOrEmpty(kom)) {
                            v.Kom += " " + kom;
                        }
                        list.add(v);
                    }
                    reader.endArray();
                } else {
                    reader.skipValue();
                }
            }
            reader.endObject();
        }
        reader.endArray();
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return list;
}

From source file:br.com.thinkti.android.filechooserfrag.fragFileChooserQuizlet.java

private List<RowData> openPage() throws Exception {
    this.errorDescription = null;
    this.errorTitle = null;

    List<RowData> list = new ArrayList<RowData>();
    InputStream inputStream = null;
    try {/*from   w w  w.j  a v  a 2  s.c  o m*/
        if (!blnPrivate) {
            URL url = new URL(getCatalogUrl());
            /*HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if ( connection.getResponseCode() >= 400 ) {
               inputStream = connection.getErrorStream();
            }
            else {
               inputStream = connection.getInputStream();
            }*/
            inputStream = org.liberty.android.fantastischmemo.downloader.quizlet.lib.makeApiCall(url,
                    _main.QuizletAccessToken);
        } else {
            inputStream = org.liberty.android.fantastischmemo.downloader.quizlet.lib
                    .getUserPrivateCardsets(_main.QuizletUser, _main.QuizletAccessToken);
        }
        JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
        if (!blnPrivate) {
            reader.beginObject();
            while (reader.hasNext()) {
                String name = reader.nextName();
                if ("total_pages".equals(name)) {
                    this.totalPages = reader.nextInt();
                    if (page > totalPages) {

                    }
                } else if ("total_results".equals(name)) {
                    this.totalResults = reader.nextInt();
                } else if ("page".equals(name)) {
                    this.page = reader.nextInt();
                } else if ("error_title".equals(name)) {
                    errorTitle = reader.nextString();
                } else if ("error_description".equals(name)) {
                    errorDescription = reader.nextString();
                } else if ("sets".equals(name)) {
                    getSets(reader, list);
                } else {
                    reader.skipValue();
                }
            }
            reader.endObject();
        } else {
            getSets(reader, list);
        }

    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return list;
}

From source file:watch.oms.omswatch.parser.OMSConfigDBParser.java

private ContentValues readSingleRowData(JsonReader reader) {
    ContentValues contentValues = new ContentValues();
    String colName = null;/*from w  ww  .j  a va  2 s.c om*/
    String colValue = null;
    try {
        reader.beginObject();

        while (reader.hasNext()) {
            colName = null;
            colValue = null;
            colName = reader.nextName();
            colValue = reader.nextString();
            if (colValue.equals(OMSConstants.NULL_STRING)) {
                colValue = OMSConstants.EMPTY_STRING;
            }

            if (!colName.equalsIgnoreCase("isdirty")) {
                contentValues.put(colName, colValue);
            }
        }
        reader.endObject();
    } catch (IOException e) {
        Log.e(TAG, "IOException:: ColName - " + (colName == null ? OMSConstants.EMPTY_STRING : colName));
        e.printStackTrace();
    }
    return contentValues;
}

From source file:watch.oms.omswatch.parser.OMSConfigDBParser.java

private List<ContentValues> readAllRowDataForTable(JsonReader reader, String pTableName) throws IOException {
    List<ContentValues> messages = new ArrayList<ContentValues>();
    ContentValues contentValues = null;//from w w  w .j  a va2  s. co m
    int skippedRowsCount = 0;
    reader.beginArray();
    while (reader.hasNext()) {
        contentValues = readSingleRowData(reader);
        if (validateRowData(contentValues)) {
            messages.add(contentValues);
        } else {
            skippedRowsCount++;
        }
    }

    if (skippedRowsCount > 0) {
        Log.d(TAG, "Skipped #" + skippedRowsCount + " records for table - " + pTableName);
    }
    reader.endArray();
    return messages;
}

From source file:ngo.music.soundcloudplayer.controller.SongController.java

/**
 * get stack of songs played//ww  w . j a  va 2 s.c  om
 * 
 * @return
 */
public ArrayList<Object[]> getSongsPlayed() {
    File file = new File(MusicPlayerService.getInstance().getApplicationContext()
            .getExternalFilesDir(Context.ACCESSIBILITY_SERVICE), filename);
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    ArrayList<Object[]> songs = new ArrayList<Object[]>();

    try {
        FileInputStream fileReader = new FileInputStream(file);
        JsonReader reader = new JsonReader(new InputStreamReader(fileReader));

        String id = null;
        reader.beginArray();

        while (reader.hasNext()) {
            reader.beginObject();

            while (reader.hasNext()) {
                Object[] object = new Object[2];
                id = reader.nextName();
                object[0] = getSong(id);
                object[1] = Integer.valueOf(reader.nextInt());
                if (object[0] != null) {
                    songs.add(object);
                }
            }

            reader.endObject();
        }

        reader.endArray();
        reader.close();
    } catch (Exception e) {
        Log.e("get songPlayed", e.toString());
        return songs;
    }
    return songs;
}