Example usage for org.json JSONObject optJSONObject

List of usage examples for org.json JSONObject optJSONObject

Introduction

In this page you can find the example usage for org.json JSONObject optJSONObject.

Prototype

public JSONObject optJSONObject(String key) 

Source Link

Document

Get an optional JSONObject associated with a key.

Usage

From source file:com.nosoop.json.VDF.java

/**
 * Recursively searches for JSONObjects, checking if they should be
 * formatted as arrays, then converted./* w w  w  .j a  v a  2  s. c om*/
 *
 * @param object An input JSONObject converted from VDF.
 * @return JSONObject containing the input JSONObject with objects changed
 * to arrays where applicable.
 * @throws JSONException
 */
private static JSONObject convertVDFArrays(JSONObject object) throws JSONException {
    JSONObject resp = new JSONObject();

    if (!object.keys().hasNext()) {
        return resp;
    }

    for (@SuppressWarnings("unchecked")
    Iterator<String> iter = object.keys(); iter.hasNext();) {
        String name = iter.next();
        JSONObject thing = object.optJSONObject(name);

        if (thing != null) {
            // Note:  Empty JSONObjects are also treated as arrays.
            if (containsVDFArray(thing)) {
                @SuppressWarnings("unchecked")
                Iterator<String> iter2 = thing.keys();
                List<String> sortingKeys = new ArrayList<String>();
                while (iter2.hasNext())
                    sortingKeys.add(iter2.next());
                Collections.sort(sortingKeys, new Comparator<String>() {
                    // Integers-as-strings comparator.
                    @Override
                    public int compare(String t, String t1) {
                        int i = Integer.parseInt(t), i1 = Integer.parseInt(t1);
                        return i - i1;
                    }
                });

                JSONArray sortedKeys = new JSONArray(sortingKeys);

                if (sortedKeys.length() > 0) {
                    JSONArray sortedObjects = thing.toJSONArray(sortedKeys);

                    for (int i = 0; i < sortedObjects.length(); i++) {
                        JSONObject arrayObject = sortedObjects.getJSONObject(i);

                        /**
                         * See if any values are also JSONObjects that
                         * should be arrays.
                         */
                        sortedObjects.put(i, convertVDFArrays(arrayObject));
                    }

                    /**
                     * If this JSONObject represents a non-empty array in
                     * VDF format, convert it to a JSONArray.
                     */
                    resp.put(name, sortedObjects);
                } else {
                    /**
                     * If this JSONObject represents an empty array, give it
                     * an empty JSONArray.
                     */
                    resp.put(name, new JSONArray());
                }
            } else {
                /**
                 * If this JSONObject is not a VDF array, see if its values
                 * are before adding.
                 */
                resp.put(name, convertVDFArrays(thing));
            }
        } else {
            /**
             * It's a plain data value. Add it in.
             */
            resp.put(name, object.get(name));
        }
    }

    /**
     * Return the converted JSONObject.
     */
    return resp;
}

From source file:com.nosoop.json.VDF.java

/**
 * Checks that a JSONObject converted from a VDF file is an array. If so,
 * the only keys in the JSONObject are a continues set of integers
 * represented by Strings starting from "0". Note that empty JSONObjects are
 * also treated as arrays.//from  w w  w  . ja  v  a2  s.  c o m
 *
 * @param object The JSONObject to check for a VDF-formatted array.
 * @return Whether or not the JSONObject is a VDF-formatted array.
 */
private static boolean containsVDFArray(JSONObject object) {
    int indices = object.length();
    int[] index = new int[indices];

    for (int i = 0; i < indices; i++) {
        index[i] = -1;
    }

    /**
     * Fail if we encounter a non-integer, if a value isn't a JSONObject,
     * or if the key is a number that is larger than the size of the array
     * (meaning we're missing a value).
     */
    for (@SuppressWarnings("unchecked")
    Iterator<String> iter = object.keys(); iter.hasNext();) {
        String name = iter.next();
        if (object.optJSONObject(name) == null) {
            return false;
        }

        try {
            int i = Integer.parseInt(name);

            if (i >= indices) {
                return false;
            }

            index[i] = i;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    // Fail if we are missing any values (e.g., 0, 1, 2, 3, 4, 5, 7, 8, 9).
    for (int i = 0; i < indices; i++) {
        if (index[i] != i) {
            return false;
        }
    }

    return true;
}

From source file:com.melniqw.instagramsdk.UserInfo.java

public static UserInfo fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    UserInfo userInfo = new UserInfo();
    userInfo.user = User.fromJSON(o);/*from w w w. j  av  a2  s .  c om*/
    userInfo.bio = o.optString("bio");
    userInfo.website = o.optString("website");
    JSONObject countsJSON = o.optJSONObject("counts");
    userInfo.media = countsJSON.optInt("media");
    userInfo.follows = countsJSON.optInt("follows");
    userInfo.followedBy = countsJSON.optInt("followed_by");
    return userInfo;
}

From source file:com.external.androidquery.service.MarketService.java

protected void showUpdateDialog(JSONObject jo) {

    if (jo == null || version != null)
        return;/*www . j a  v  a2s .c  o m*/

    if (!isActive())
        return;

    JSONObject dia = jo.optJSONObject("dialog");

    String update = dia.optString("update", "Update");
    String skip = dia.optString("skip", "Skip");
    String rate = dia.optString("rate", "Rate");
    //String message = dia.optString("body", "");
    String body = dia.optString("wbody", "");
    String title = dia.optString("title", "Update Available");

    AQUtility.debug("wbody", body);

    version = jo.optString("version", null);

    Drawable icon = getAppIcon();

    Context context = act;

    final AlertDialog dialog = new AlertDialog.Builder(context).setIcon(icon).setTitle(title)
            .setPositiveButton(rate, handler).setNeutralButton(skip, handler).setNegativeButton(update, handler)
            .create();

    dialog.setMessage(Html.fromHtml(patchBody(body), null, handler));

    aq.show(dialog);

    return;

}

From source file:uguess.qucai.com.merchant.business.user.protocol.GetPublicKeyProcess.java

@Override
protected void onResult(JSONObject o) {
    //???/*w w  w  .j  a v  a  2 s .c  o  m*/
    int value = o.optInt("result_code");
    if (value == 0) {
        /**
         * ??
         */
        JSONObject key = o.optJSONObject("body");
        if (key != null) {
            String keyString = key.optString("public_key");
            Cache.getInstance().setPublicKey(keyString);
        } else {

        }
    }
    setProcessStatus(value);
}

From source file:uguess.qucai.com.merchant.business.user.protocol.GetPublicKeyProcess.java

public void storePublicKey(JSONObject o) {
    JSONObject key = o.optJSONObject("body");
    if (key == null && MAX_NUM > -1) {
        QucaiApplication.getInstance().getPublicKey();
        MAX_NUM--;/*w w  w.j  a  v a 2 s .c om*/
    } else if (key != null) {
        String keyString = key.optString("public_key");
        Cache.getInstance().setPublicKey(keyString);
    } else {

    }
}

From source file:org.jandroid2cloud.connection.ChannelHandler.java

@Override
public void message(String rawMsg) {
    logger.debug("Received message from server:" + rawMsg);

    try {/*  w  ww  . ja v  a  2 s . c o  m*/
        JSONObject jsonMessage = new JSONObject(new JSONTokener(rawMsg));
        JSONObject links = (JSONObject) jsonMessage.opt("links");
        if (links == null) {
            JSONObject link = jsonMessage.optJSONObject("link");
            handleLink(link);
        } else {
            Iterator it = links.keys();
            while (it.hasNext()) {
                String s = (String) it.next();
                if (s != null && !s.isEmpty()) {
                    JSONObject o = links.getJSONObject(s);
                    handleLink(o);
                }
            }
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("links", rawMsg);
        String response = oauth.makeRequest("http://" + config.getHost() + "/markread", Verb.POST, params);
        logger.debug("Marked message as read");
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (NetworkException e) {
        logger.error(NotificationAppender.MARKER, "Could not mark links as read.\n"
                + "You will not receive more links until that is done.\n" + "See log for details", e);
    }
}

From source file:org.eclipse.orion.server.cf.handlers.v1.AppsHandlerV1.java

@Override
protected CFJob handlePut(App resource, HttpServletRequest request, HttpServletResponse response,
        final String pathString) {
    final JSONObject targetJSON2 = extractJSONData(
            IOUtilities.getQueryParameter(request, CFProtocolConstants.KEY_TARGET));

    IPath path = pathString != null ? new Path(pathString) : new Path("");
    final String appGuid = path.segment(0);
    boolean addRoute = "routes".equals(path.segment(1));
    final String routeGuid = addRoute ? path.segment(2) : null;

    if (addRoute)
        return new CFJob(request, false) {
            @Override//from w  w  w.j a  va  2  s .com
            protected IStatus performJob() {
                try {
                    ComputeTargetCommand computeTarget = new ComputeTargetCommand(this.userId, targetJSON2);
                    IStatus status = computeTarget.doIt();
                    if (!status.isOK())
                        return status;
                    Target target = computeTarget.getTarget();

                    GetAppByGuidCommand getAppByGuid = new GetAppByGuidCommand(target.getCloud(), appGuid);
                    IStatus getAppByGuidStatus = getAppByGuid.doIt();
                    if (!getAppByGuidStatus.isOK())
                        return getAppByGuidStatus;
                    App app = getAppByGuid.getApp();

                    GetRouteByGuidCommand getRouteByGuid = new GetRouteByGuidCommand(target.getCloud(),
                            routeGuid);
                    IStatus getRouteByGuidStatus = getRouteByGuid.doIt();
                    if (!getRouteByGuidStatus.isOK())
                        return getRouteByGuidStatus;
                    Route route = getRouteByGuid.getRoute();

                    MapRouteCommand unmapRoute = new MapRouteCommand(target, app, route.getGuid());
                    return unmapRoute.doIt();
                } catch (Exception e) {
                    String msg = NLS.bind("Failed to handle request for {0}", pathString); //$NON-NLS-1$
                    ServerStatus status = new ServerStatus(IStatus.ERROR,
                            HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
                    logger.error(msg, e);
                    return status;
                }
            }
        };

    final JSONObject jsonData = extractJSONData(request);
    final JSONObject targetJSON = jsonData.optJSONObject(CFProtocolConstants.KEY_TARGET);

    final String state = jsonData.optString(CFProtocolConstants.KEY_STATE, null);
    final String appName = jsonData.optString(CFProtocolConstants.KEY_NAME, null);
    final String contentLocation = ServletResourceHandler.toOrionLocation(request,
            jsonData.optString(CFProtocolConstants.KEY_CONTENT_LOCATION, null));

    /* default application startup is one minute */
    int userTimeout = jsonData.optInt(CFProtocolConstants.KEY_TIMEOUT, 60);
    final int timeout = (userTimeout > 0) ? userTimeout : 0;

    /* TODO: The force shouldn't be always with us */
    final boolean force = jsonData.optBoolean(CFProtocolConstants.KEY_FORCE, true);

    return new CFJob(request, false) {
        @Override
        protected IStatus performJob() {
            try {
                ComputeTargetCommand computeTarget = new ComputeTargetCommand(this.userId, targetJSON);
                IStatus status = computeTarget.doIt();
                if (!status.isOK())
                    return status;
                Target target = computeTarget.getTarget();

                /* parse the application manifest */
                String manifestAppName = null;
                ParseManifestCommand parseManifestCommand = null;
                if (contentLocation != null) {
                    parseManifestCommand = new ParseManifestCommand(target, this.userId, contentLocation);
                    status = parseManifestCommand.doIt();
                    if (!status.isOK())
                        return status;

                    /* get the manifest name */
                    ManifestParseTree manifest = parseManifestCommand.getManifest();
                    if (manifest != null) {
                        ManifestParseTree applications = manifest.get(CFProtocolConstants.V2_KEY_APPLICATIONS);
                        if (applications.getChildren().size() > 0)
                            manifestAppName = applications.get(0).get(CFProtocolConstants.V2_KEY_NAME)
                                    .getValue();
                    }
                }

                GetAppCommand getAppCommand = new GetAppCommand(target,
                        appName != null ? appName : manifestAppName);
                status = getAppCommand.doIt();
                App app = getAppCommand.getApp();

                if (CFProtocolConstants.KEY_STARTED.equals(state)) {
                    if (!status.isOK())
                        return status;
                    return new StartAppCommand(target, app, timeout).doIt();
                } else if (CFProtocolConstants.KEY_STOPPED.equals(state)) {
                    if (!status.isOK())
                        return status;
                    return new StopAppCommand(target, app).doIt();
                } else {
                    if (parseManifestCommand == null) {
                        String msg = NLS.bind("Failed to handle request for {0}", pathString); //$NON-NLS-1$
                        status = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                msg, null);
                        logger.error(msg);
                        return status;
                    }
                }

                // push new application
                if (app == null)
                    app = new App();

                app.setName(appName != null ? appName : manifestAppName);
                app.setManifest(parseManifestCommand.getManifest());

                status = new PushAppCommand(target, app, parseManifestCommand.getAppStore(), force).doIt();
                if (!status.isOK())
                    return status;

                // get the app again
                getAppCommand = new GetAppCommand(target, app.getName());
                getAppCommand.doIt();
                app = getAppCommand.getApp();
                app.setManifest(parseManifestCommand.getManifest());

                new StartAppCommand(target, app).doIt();

                return status;
            } catch (Exception e) {
                String msg = NLS.bind("Failed to handle request for {0}", pathString); //$NON-NLS-1$
                ServerStatus status = new ServerStatus(IStatus.ERROR,
                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
                logger.error(msg, e);
                return status;
            }
        }
    };
}

From source file:org.schedulesdirect.grabber.Grabber.java

private boolean logoCacheInvalid(JSONObject station) throws JSONException, IOException {
    JSONObject logo = station.optJSONObject("logo");
    if (logo != null) {
        String callsign = station.getString("callsign");
        String cached = logoCache.optString(callsign, null);
        if (cached != null)
            return !cached.equals(logo.optString("md5"));
    }//from ww w  .  java  2s.c o  m
    return true;
}

From source file:weathernotificationservice.wns.activities.MainActivity.java

private ParseResult parseTodayJson(String result) {
    try {//from   ww  w. j av a2s.c  o m
        JSONObject reader = new JSONObject(result);

        final String code = reader.optString("cod");
        if ("404".equals(code)) {
            return ParseResult.CITY_NOT_FOUND;
        }

        String city = reader.getString("name");
        String country = "";
        JSONObject countryObj = reader.optJSONObject("sys");
        if (countryObj != null) {
            country = countryObj.getString("country");
            todayWeather.setSunrise(countryObj.getString("sunrise"));
            todayWeather.setSunset(countryObj.getString("sunset"));
        }
        todayWeather.setCity(city);
        todayWeather.setCountry(country);

        JSONObject coordinates = reader.getJSONObject("coord");
        if (coordinates != null) {
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
            sp.edit().putFloat("latitude", (float) coordinates.getDouble("lon"))
                    .putFloat("longitude", (float) coordinates.getDouble("lat")).commit();
        }

        JSONObject main = reader.getJSONObject("main");

        todayWeather.setTemperature(main.getString("temp"));
        todayWeather.setDescription(reader.getJSONArray("weather").getJSONObject(0).getString("description"));
        JSONObject windObj = reader.getJSONObject("wind");
        todayWeather.setWind(windObj.getString("speed"));
        if (windObj.has("deg")) {
            todayWeather.setWindDirectionDegree(windObj.getDouble("deg"));
        } else {
            Log.e("parseTodayJson", "No wind direction available");
            todayWeather.setWindDirectionDegree(null);
        }
        todayWeather.setPressure(main.getString("pressure"));
        todayWeather.setHumidity(main.getString("humidity"));

        JSONObject rainObj = reader.optJSONObject("rain");
        String rain;
        if (rainObj != null) {
            rain = getRainString(rainObj);
        } else {
            JSONObject snowObj = reader.optJSONObject("snow");
            if (snowObj != null) {
                rain = getRainString(snowObj);
            } else {
                rain = "0";
            }
        }
        todayWeather.setRain(rain);

        final String idString = reader.getJSONArray("weather").getJSONObject(0).getString("id");
        todayWeather.setId(idString);
        todayWeather.setIcon(
                setWeatherIcon(Integer.parseInt(idString), Calendar.getInstance().get(Calendar.HOUR_OF_DAY)));

        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this)
                .edit();
        editor.putString("lastToday", result);
        editor.commit();

    } catch (JSONException e) {
        Log.e("JSONException Data", result);
        e.printStackTrace();
        return ParseResult.JSON_EXCEPTION;
    }

    return ParseResult.OK;
}