Example usage for android.util JsonReader nextString

List of usage examples for android.util JsonReader nextString

Introduction

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

Prototype

public String nextString() throws IOException 

Source Link

Document

Returns the JsonToken#STRING string value of the next token, consuming it.

Usage

From source file:fiskinfoo.no.sintef.fiskinfoo.Http.BarentswatchApiRetrofit.BarentswatchApi.java

public BarentswatchApi() {
    String directoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .toString();/* www.j a va  2s  .  com*/
    String fileName = directoryPath + "/FiskInfo/api_setting.json";
    File file = new File(fileName);
    String environment = null;

    if (file.exists()) {
        InputStream inputStream;
        InputStreamReader streamReader;
        JsonReader jsonReader;

        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            streamReader = new InputStreamReader(inputStream, "UTF-8");
            jsonReader = new JsonReader(streamReader);

            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                String name = jsonReader.nextName();
                if (name.equals("environment")) {
                    environment = jsonReader.nextString();
                } else {
                    jsonReader.skipValue();
                }
            }
            jsonReader.endObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

    targetProd = !"pilot".equals(environment);
    currentPath = targetProd ? barentsWatchProdAddress : barentsWatchPilotAddress;
    BARENTSWATCH_API_ENDPOINT = currentPath + "/api/v1/geodata";

    Executor httpExecutor = Executors.newSingleThreadExecutor();
    MainThreadExecutor callbackExecutor = new MainThreadExecutor();
    barentswatchApi = initializeBarentswatchAPI(httpExecutor, callbackExecutor);
}

From source file:at.ac.tuwien.caa.docscan.logic.DataLog.java

private ShotLog readShotLog(JsonReader reader) throws IOException, ParseException {

    GPS gps = null;//from w w w  .  ja  v a  2s.c  o  m
    String dateString, fileName = null;
    Date date = null;
    boolean seriesMode = false;

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals(FILE_NAME)) {
            fileName = reader.nextString();
        } else if (name.equals(DATE_NAME)) {
            dateString = reader.nextString();
            if (dateString != null)
                date = string2Date(dateString);
        } else if (name.equals(GPS_NAME)) {
            gps = readGPS(reader);
        } else if (name.equals(SERIES_MODE_NAME)) {
            seriesMode = reader.nextBoolean();
        }

    }
    reader.endObject();

    ShotLog shotLog = new ShotLog(fileName, gps, date, seriesMode);
    return shotLog;

}

From source file:com.tcity.android.ui.info.BuildInfoTask.java

private void handleResponse(@NotNull HttpResponse response) throws IOException, ParseException {
    JsonReader reader = new JsonReader(new InputStreamReader(response.getEntity().getContent()));

    //noinspection TryFinallyCanBeTryWithResources
    try {// www . j av  a2 s.co m
        reader.beginObject();

        BuildInfoData data = new BuildInfoData();
        SimpleDateFormat dateFormat = new SimpleDateFormat(Common.TEAMCITY_DATE_FORMAT);

        while (reader.hasNext()) {
            switch (reader.nextName()) {
            case "status":
                if (data.status == null) {
                    data.status = com.tcity.android.Status.valueOf(reader.nextString());
                }
                break;
            case "running":
                if (reader.nextBoolean()) {
                    data.status = com.tcity.android.Status.RUNNING;
                }
                break;
            case "branchName":
                data.branch = reader.nextString();
                break;
            case "defaultBranch":
                data.isBranchDefault = reader.nextBoolean();
                break;
            case "statusText":
                data.result = reader.nextString();
                break;
            case "waitReason":
                data.waitReason = reader.nextString();
                break;
            case "queuedDate":
                data.queued = dateFormat.parse(reader.nextString());
                break;
            case "startDate":
                data.started = dateFormat.parse(reader.nextString());
                break;
            case "finishDate":
                data.finished = dateFormat.parse(reader.nextString());
                break;
            case "agent":
                data.agent = getAgentName(reader);
                break;
            default:
                reader.skipValue();
            }
        }

        myResult = data;

        reader.endObject();
    } finally {
        reader.close();
    }
}

From source file:com.tcity.android.ui.info.BuildArtifactsTask.java

private void handleFiles(@NotNull JsonReader reader) throws IOException {
    reader.beginArray();/*from   w ww . j ava 2s  .  co  m*/

    List<BuildArtifact> result = new ArrayList<>();

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

        long size = -1;
        String name = null;
        String contentHref = null;
        String childrenHref = null;

        while (reader.hasNext()) {
            switch (reader.nextName()) {
            case "size":
                size = reader.nextLong();
                break;
            case "name":
                name = reader.nextString();
                break;
            case "children":
                childrenHref = getHref(reader);
                break;
            case "content":
                contentHref = getHref(reader);
                break;
            default:
                reader.skipValue();
            }
        }

        if (name == null) {
            throw new IllegalStateException("Invalid artifacts json: \"name\" is absent");
        }

        if (contentHref == null && childrenHref == null) {
            throw new IllegalStateException("Invalid artifacts json: \"content\" and \"children\" are absent");
        }

        result.add(new BuildArtifact(size, name, contentHref, childrenHref));

        reader.endObject();
    }

    reader.endArray();

    myResult = result;
}

From source file:com.morlunk.leeroy.LeeroyUpdateService.java

private void handleCheckUpdates(Intent intent, boolean notify, ResultReceiver receiver) {
    List<LeeroyApp> appList = LeeroyApp.getApps(getPackageManager());

    if (appList.size() == 0) {
        return;/*from  ww  w. j a va  2  s  .  c om*/
    }

    List<LeeroyAppUpdate> updates = new LinkedList<>();
    List<LeeroyApp> notUpdatedApps = new LinkedList<>();
    List<LeeroyException> exceptions = new LinkedList<>();
    for (LeeroyApp app : appList) {
        try {
            String paramUrl = app.getJenkinsUrl() + "/api/json?tree=lastSuccessfulBuild[number,url]";
            URL url = new URL(paramUrl);
            URLConnection conn = url.openConnection();
            Reader reader = new InputStreamReader(conn.getInputStream());

            JsonReader jsonReader = new JsonReader(reader);
            jsonReader.beginObject();
            jsonReader.nextName();
            jsonReader.beginObject();

            int latestSuccessfulBuild = 0;
            String buildUrl = null;
            while (jsonReader.hasNext()) {
                String name = jsonReader.nextName();
                if ("number".equals(name)) {
                    latestSuccessfulBuild = jsonReader.nextInt();
                } else if ("url".equals(name)) {
                    buildUrl = jsonReader.nextString();
                } else {
                    throw new RuntimeException("Unknown key " + name);
                }
            }
            jsonReader.endObject();
            jsonReader.endObject();
            jsonReader.close();

            if (latestSuccessfulBuild > app.getJenkinsBuild()) {
                LeeroyAppUpdate update = new LeeroyAppUpdate();
                update.app = app;
                update.newBuild = latestSuccessfulBuild;
                update.newBuildUrl = buildUrl;
                updates.add(update);
            } else {
                notUpdatedApps.add(app);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            CharSequence appName = app.getApplicationInfo().loadLabel(getPackageManager());
            exceptions.add(new LeeroyException(app, getString(R.string.invalid_url, appName), e));
        } catch (IOException e) {
            e.printStackTrace();
            exceptions.add(new LeeroyException(app, e));
        }
    }

    if (notify) {
        NotificationManagerCompat nm = NotificationManagerCompat.from(this);
        if (updates.size() > 0) {
            NotificationCompat.Builder ncb = new NotificationCompat.Builder(this);
            ncb.setSmallIcon(R.drawable.ic_stat_update);
            ncb.setTicker(getString(R.string.updates_available));
            ncb.setContentTitle(getString(R.string.updates_available));
            ncb.setContentText(getString(R.string.num_updates, updates.size()));
            ncb.setPriority(NotificationCompat.PRIORITY_LOW);
            ncb.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            Intent appIntent = new Intent(this, AppListActivity.class);
            appIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            ncb.setContentIntent(
                    PendingIntent.getActivity(this, 0, appIntent, PendingIntent.FLAG_CANCEL_CURRENT));
            ncb.setAutoCancel(true);
            NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
            for (LeeroyAppUpdate update : updates) {
                CharSequence appName = update.app.getApplicationInfo().loadLabel(getPackageManager());
                style.addLine(getString(R.string.notify_app_update, appName, update.app.getJenkinsBuild(),
                        update.newBuild));
            }
            style.setSummaryText(getString(R.string.app_name));
            ncb.setStyle(style);
            ncb.setNumber(updates.size());
            nm.notify(NOTIFICATION_UPDATE, ncb.build());
        }

        if (exceptions.size() > 0) {
            NotificationCompat.Builder ncb = new NotificationCompat.Builder(this);
            ncb.setSmallIcon(R.drawable.ic_stat_error);
            ncb.setTicker(getString(R.string.error_checking_updates));
            ncb.setContentTitle(getString(R.string.error_checking_updates));
            ncb.setContentText(getString(R.string.click_to_retry));
            ncb.setPriority(NotificationCompat.PRIORITY_LOW);
            ncb.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            ncb.setContentIntent(PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
            ncb.setAutoCancel(true);
            ncb.setNumber(exceptions.size());
            nm.notify(NOTIFICATION_ERROR, ncb.build());
        }
    }

    if (receiver != null) {
        Bundle results = new Bundle();
        results.putParcelableArrayList(EXTRA_UPDATE_LIST, new ArrayList<>(updates));
        results.putParcelableArrayList(EXTRA_NO_UPDATE_LIST, new ArrayList<>(notUpdatedApps));
        results.putParcelableArrayList(EXTRA_EXCEPTION_LIST, new ArrayList<>(exceptions));
        receiver.send(0, results);
    }
}

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

/**
 * Determines what the next value is and returns it as the appropriate basic type or a custom
 * object, a collection, a {@link JSONObject}, or {@link JSONArray}.
 *
 * @param reader The JsonReader to use. The next token ({@link JsonReader#peek()} must be a
 * value.//  w w  w.jav a  2 s  . co  m
 * @param convertJsonTypes If {@code true}, and the next value is a JSONArray, it will be
 * converted to a Collection, and if the next value is a JSONObject, it will be parsed into the
 * appropriate object type. If {@code false}, a raw JSONArray or JSONObject will be returned.
 *
 * @return The next value. If the next value is {@link JsonToken#NULL}, then {@code null} is
 * returned.
 */
public static Object parseNextValue(JsonReader reader, boolean convertJsonTypes) throws IOException {
    JsonToken nextToken = reader.peek();
    switch (nextToken) {
    case BEGIN_ARRAY:
        if (convertJsonTypes) {
            Collection<Object> collection = new ArrayList<>();
            parseJsonArray(reader, collection, null, Object.class, null, null);
            return collection;
        } else {
            return parseAsJsonArray(reader, null);
        }
    case BEGIN_OBJECT:
        if (convertJsonTypes) {
            return parseJsonObject(reader, null, null, null);
        } else {
            return parseAsJsonObject(reader, null);
        }
    case BOOLEAN:
        return reader.nextBoolean();
    case NUMBER:
    case STRING:
        return reader.nextString();
    case NULL:
        reader.nextNull();
        return null;

    default:
        throw new IllegalStateException("Unexpected token: " + nextToken);
    }
}

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.//from ww  w .j ava2 s  .  c  o m
 * <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:br.com.thinkti.android.filechooserfrag.fragFileChooserQuizlet.java

RowData parseSetJson(JsonReader reader) throws IOException {
    reader.beginObject();/*from w  w w.j  a  v  a 2s.c  om*/
    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();/*from w  w w . j  av a  2  s .c om*/
    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: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   w w  w  .  j a  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();
}