Example usage for android.util JsonReader beginObject

List of usage examples for android.util JsonReader beginObject

Introduction

In this page you can find the example usage for android.util JsonReader beginObject.

Prototype

public void beginObject() throws IOException 

Source Link

Document

Consumes the next token from the JSON stream and asserts that it is the beginning of a new object.

Usage

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

RowData parseSetJson(JsonReader reader) throws IOException {
    reader.beginObject();
    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 {/*from  w  w w .ja v a  2s . co m*/
            reader.skipValue();
        }
    }
    reader.endObject();
    return rowData;
}

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

/**
 * Parse an array that has only non-array 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 ww w . ja v  a2 s  . c  o  m
 * @param collection The Collection to populate. The parametrization should match {@code
 * typeClass}.
 * @param itemParser The parser to use for items of the array. May be null.
 * @param typeClass The type of items to expect in the array. May not be null, but may be
 * Object.class.
 * @param key The key corresponding to the current value. This is used to make more useful error
 * messages.
 */
private static <T> void parseFlatJsonArray(JsonReader reader, Collection<T> collection,
        JsonObjectParser<T> itemParser, Class<T> typeClass, String key) throws IOException {
    if (handleNull(reader)) {
        return;
    }

    Converter<T> converter = null;
    if (Converters.isConvertibleFromString(typeClass)) {
        converter = Converters.getConverter(typeClass);
    }

    final String discriminationName = ContextHolder.getContext().getSettings().getDiscriminationName();

    reader.beginArray();
    while (reader.hasNext()) {
        Object nextValue;
        final JsonToken nextToken = reader.peek();
        if (itemParser != null && nextToken == JsonToken.BEGIN_OBJECT) {
            reader.beginObject();
            nextValue = itemParser.parseJsonObject(null, reader, discriminationName, null);
            reader.endObject();
        } else if (converter != null && (nextToken == JsonToken.NUMBER || nextToken == JsonToken.STRING)) {
            nextValue = converter.convert(reader.nextString());
        } else {
            nextValue = parseNextValue(reader);
        }

        if (typeClass.isInstance(nextValue)) {
            // This is safe since we are calling class.isInstance()
            @SuppressWarnings("unchecked")
            T toAdd = (T) nextValue;
            collection.add(toAdd);
        } else {
            throw new IllegalStateException(
                    String.format(Locale.US, "Could not convert value in array at \"%s\" to %s from %s.", key,
                            typeClass.getCanonicalName(), getClassName(nextValue)));
        }
    }
    reader.endArray();
}

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

typVok parseSetDataJson(JsonReader reader) throws IOException {
    reader.beginObject();
    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;//from ww w. j  a va 2 s  .  co  m
        } 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<RowData> openPage() throws Exception {
    this.errorDescription = null;
    this.errorTitle = null;

    List<RowData> list = new ArrayList<RowData>();
    InputStream inputStream = null;
    try {//  w  w w.j a  v a  2s .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: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 {/*from  ww w  .  ja  v a 2  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:watch.oms.omswatch.parser.OMSConfigDBParser.java

private ContentValues readSingleRowData(JsonReader reader) {
    ContentValues contentValues = new ContentValues();
    String colName = null;/* www . j  a v  a  2 s.com*/
    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:com.dalaran.async.task.http.AbstractHTTPService.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected List<ContentValues> parseJson(JsonReader reader) throws IOException {

    List<ContentValues> contentValueses = new ArrayList<ContentValues>();
    ContentValues values = new ContentValues();
    Long threadId = 0L;/* ww  w  .  ja  v a  2  s .  c o  m*/
    boolean notEnd = true;
    String name = "";
    if (reader.hasNext()) { //todo android.util.MalformedJsonException: Use JsonReader.setLenient(true)
        do {
            switch (reader.peek()) {
            case BEGIN_OBJECT:
                values = new ContentValues();
                if (threadId != 0) {
                    values.put("threadId", threadId);
                }
                reader.beginObject();
                break;
            case BEGIN_ARRAY:
                if (values != null && values.getAsLong("threadId") != null) {
                    threadId = values.getAsLong("threadId");
                }
                reader.beginArray();
                break;
            case BOOLEAN:
                values.put(name, reader.nextBoolean());
                break;
            case END_ARRAY:
                reader.endArray();
                break;
            case END_DOCUMENT:
                notEnd = false;
                break;
            case END_OBJECT:
                contentValueses.add(values);
                reader.endObject();
                break;
            case NAME:
                name = reader.nextName();
                break;
            case NULL:
                reader.nextNull();
                break;
            case NUMBER:
                values.put(name, reader.nextDouble());
                break;
            case STRING:
                values.put(name, reader.nextString());
                break;
            default:
                reader.skipValue();
            }
        } while (notEnd);
    }
    return contentValueses;
}

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

/**
 * get stack of songs played//from   w ww .  j a  va2  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;
}

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

/**
 * Parses Service response and stores into respective DB table.
 * /*from w  w  w  .jav  a2  s.com*/
 * @param pStringReader
 */
private void readJsonStream(Reader pStringReader) {
    double latestModifiedTimeStamp = 0.0f;
    JsonReader reader = null;
    List<ContentValues> rows = null;
    String tableName = null;
    ExecutorService executor = Executors.newFixedThreadPool(10);
    final String VISITED_DATE = "visiteddate";
    OMSServerMapperHelper servermapperhelper = new OMSServerMapperHelper();
    final String DB_PROCESS_DURATION = "dbprocessduration";
    final String SERVER_PROCESS_DURATION = "serverprocessduration";

    try {
        Log.d(TAG, "@@@@@@@@@@ Config DB Tables Start @@@@@@@@@@");
        reader = new JsonReader(pStringReader);
        reader.setLenient(true);
        reader.beginObject();
        // Iterate through each table data
        while (reader.hasNext()) {
            tableName = reader.nextName();
            if (tableName.equals(VISITED_DATE)) {

                latestModifiedTimeStamp = reader.nextDouble();

                /*servermapperhelper.updateModifiedTimeStampForAppsTable(
                       latestModifiedTimeStamp);*/
                /*if (Integer.parseInt(OMSApplication
                      .getInstance().getAppId()) == 10) {
                   servermapperhelper
                .updateModifiedTimeStampForVisitedDateMapper(
                      OMSApplication
                            .getInstance()
                            .getEditTextHiddenVal(),
                      latestModifiedTimeStamp);
                }*/
                continue;
            }
            if (tableName.equals(OMSConstants.NULL_STRING)) {
                continue;
            }
            //Fetch dbprocess duration serverprocess duration
            else if (DB_PROCESS_DURATION.equalsIgnoreCase(tableName)) {
                String dbDuration = reader.nextString();
                OMSApplication.getInstance().setDatabaseProcessDuration(dbDuration);
                Log.i(TAG, "DB Process Duration" + dbDuration);
                continue;
            }
            if (SERVER_PROCESS_DURATION.equalsIgnoreCase(tableName)) {
                String serverProcessDuration = reader.nextString();
                OMSApplication.getInstance().setServerProcessDuration(serverProcessDuration);
                Log.i(TAG, "server process duration " + serverProcessDuration);
                continue;
            }
            rows = readAllRowDataForTable(reader, tableName);

            Runnable worker = new DbWorkerThread(tableName, rows);
            executor.execute(worker);
        }
        reader.endObject();
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        Log.d(TAG, "@@@@@@@@@@ Config DB Tables End @@@@@@@@@@");
        // Update Apps Table
        Log.d(TAG, "@@@@@@@@@@ Updating AppsTable with ConfigLastModifieddate:" + latestModifiedTimeStamp);
        servermapperhelper.updateModifiedTimeStampForAppsTable(latestModifiedTimeStamp);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {

        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            Log.e(TAG, "IOException occurred while loading file from Assets folder." + e.getMessage());
            e.printStackTrace();
        }

    }

}

From source file:watch.oms.omswatch.actioncenter.helpers.WatchTransDBParser.java

private ContentValues readSingleRowData(JsonReader reader, List<String> transColsSet, String tableName) {
    ContentValues contentValues = new ContentValues();
    String colName = null;//  w w  w .  j av  a 2s  .  c om
    String colValue = null;
    try {
        reader.beginObject();

        while (reader.hasNext()) {
            colName = null;
            colValue = null;
            colName = reader.nextName();
            colValue = reader.nextString();
            //      Log.d("TAG","ColName::::"+colName+"::::"+"ColVal:::"+colValue);

            // If Table Name is null, return empty ContentValues
            if (tableName != null) {
                if ((transColsSet != null && !transColsSet.isEmpty()) && transColsSet.contains(colName)) {
                    if (TextUtils.isEmpty(colValue) || colValue.equals(OMSConstants.NULL_STRING)) {
                        colValue = OMSConstants.EMPTY_STRING;
                    }
                    contentValues.put(colName, colValue);
                } else {
                    // Log.d(TAG, "Ignored column :" + colName
                    // + " from Table - " + tableName);
                }
            }
        }
        reader.endObject();
    } catch (IOException e) {
        Log.e(TAG, "IOException:: ColName - " + (colName == null ? OMSConstants.EMPTY_STRING : colName));
        e.printStackTrace();
    }
    return contentValues;
}