Example usage for org.json JSONObject opt

List of usage examples for org.json JSONObject opt

Introduction

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

Prototype

public Object opt(String key) 

Source Link

Document

Get an optional value associated with a key.

Usage

From source file:com.panchosoft.appspy.models.iTunesProxy.java

public iTunesApp obtenerAppPorID(String appID) {
        // Hacemos una bsqueda en iTunes
        String datos_json = obtenerDatosAppJSON(appID);

        if (datos_json == null || datos_json.length() == 0) {
            return null;
        }//w w  w .j a  v a  2 s. c o  m

        try {
            JSONObject ob = new JSONObject(datos_json);

            if (ob == null) {
                return null;
            }

            JSONArray resultados = ob.getJSONArray("results");

            if (resultados == null) {
                return null;
            }

            JSONObject appdata = resultados.getJSONObject(0);

            if (appdata == null) {
                return null;
            }

            // Creamos el objeto iTunesApp
            iTunesApp app = new iTunesApp();
            app.setArtistId(appdata.opt("artistId").toString());
            app.setArtistName(appdata.optString("artistName"));
            app.setArtistViewUrl(appdata.optString("artistViewUrl"));
            app.setArtworkUrl100(appdata.optString("artworkUrl100"));
            app.setArtworkUrl60(appdata.optString("artworkUrl60"));
            app.setContentAdvisoryRating(appdata.optString("advisorRating"));
            app.setDescription(appdata.optString("description"));
            app.setFileSizeBytes(appdata.optString("fileSizeBytes"));
            // Generos
            JSONArray generos = appdata.getJSONArray("genreIds");
            String[] generosApp = new String[generos.length()];
            for (int i = 0; i < generos.length(); i++) {
                generosApp[i] = generos.getString(i);
            }
            app.setGenreIds(generosApp);
            // Generos nombres
            generos = appdata.getJSONArray("genres");
            generosApp = new String[generos.length()];
            for (int i = 0; i < generos.length(); i++) {
                generosApp[i] = generos.getString(i);
            }
            app.setGenres(generosApp);
            // Lenguajes
            JSONArray lenguajes = appdata.getJSONArray("genres");
            String[] lenguajesApp = new String[lenguajes.length()];
            for (int i = 0; i < lenguajes.length(); i++) {
                lenguajesApp[i] = lenguajes.getString(i);
            }
            app.setLanguageCodesISO2(lenguajesApp);
            app.setPrice(appdata.optString("price"));
            app.setPrimaryGenreId(appdata.optString("primaryGenreId"));
            app.setPrimaryGenreName(appdata.optString("primaryGenreName"));
            app.setReleaseDate(appdata.optString("releaseDate"));
            // Capturas
            JSONArray capturas = appdata.getJSONArray("screenshotUrls");
            String[] capturasApp = new String[capturas.length()];
            for (int i = 0; i < capturas.length(); i++) {
                capturasApp[i] = capturas.getString(i);
            }
            app.setScreenshotUrls(capturasApp);
            app.setSellerName(appdata.optString("sellerName"));
            app.setSellerUrl(appdata.optString("sellerUrl"));
            // Dispositivos soportados
            JSONArray dispositivos = appdata.getJSONArray("supportedDevices");
            String[] dispositivosApp = new String[dispositivos.length()];
            for (int i = 0; i < dispositivos.length(); i++) {
                dispositivosApp[i] = dispositivos.getString(i);
            }
            app.setSupportedDevices(dispositivosApp);
            app.setTrackCensoredName(appdata.optString("trackCensoredName"));
            app.setTrackName(appdata.optString("trackName"));
            app.setTrackViewUrl(appdata.optString("trackViewUrl"));
            app.setVersion(appdata.optString("version"));

            return app;
        } catch (JSONException ex) {
            Logger.getLogger("com.panchosoft.itunes").log(Level.WARNING, "Error: " + ex.getMessage());
        }

        return null;
    }

From source file:com.panchosoft.appspy.models.iTunesProxy.java

public iTunesApp obtenerApp(String appName) {

        // Hacemos una bsqueda en iTunes
        String datos_json = buscarDatosAppJSON(appName, 1);

        if (datos_json == null || datos_json.length() == 0) {
            return null;
        }//from   w  w  w. ja  v a2  s .c  o m

        try {
            JSONObject ob = new JSONObject(datos_json);

            if (ob == null) {
                return null;
            }

            JSONArray resultados = ob.getJSONArray("results");

            if (resultados == null) {
                return null;
            }

            JSONObject appdata = resultados.getJSONObject(0);

            if (appdata == null) {
                return null;
            }

            // Creamos el objeto iTunesApp
            iTunesApp app = new iTunesApp();
            app.setArtistId(appdata.opt("artistId").toString());
            app.setArtistName(appdata.optString("artistName"));
            app.setArtistViewUrl(appdata.optString("artistViewUrl"));
            app.setArtworkUrl100(appdata.optString("artworkUrl100"));
            app.setArtworkUrl60(appdata.optString("artworkUrl60"));
            app.setContentAdvisoryRating(appdata.optString("advisorRating"));
            app.setDescription(appdata.optString("description"));
            app.setFileSizeBytes(appdata.optString("fileSizeBytes"));
            // Generos
            JSONArray generos = appdata.getJSONArray("genreIds");
            String[] generosApp = new String[generos.length()];
            for (int i = 0; i < generos.length(); i++) {
                generosApp[i] = generos.getString(i);
            }
            app.setGenreIds(generosApp);
            // Generos nombres
            generos = appdata.getJSONArray("genres");
            generosApp = new String[generos.length()];
            for (int i = 0; i < generos.length(); i++) {
                generosApp[i] = generos.getString(i);
            }
            app.setGenres(generosApp);
            // Lenguajes
            JSONArray lenguajes = appdata.getJSONArray("genres");
            String[] lenguajesApp = new String[lenguajes.length()];
            for (int i = 0; i < lenguajes.length(); i++) {
                lenguajesApp[i] = lenguajes.getString(i);
            }
            app.setLanguageCodesISO2(lenguajesApp);
            app.setPrice(appdata.optString("price"));
            app.setPrimaryGenreId(appdata.optString("primaryGenreId"));
            app.setPrimaryGenreName(appdata.optString("primaryGenreName"));
            app.setReleaseDate(appdata.optString("releaseDate"));
            // Capturas
            JSONArray capturas = appdata.getJSONArray("screenshotUrls");
            String[] capturasApp = new String[capturas.length()];
            for (int i = 0; i < capturas.length(); i++) {
                capturasApp[i] = capturas.getString(i);
            }
            app.setScreenshotUrls(capturasApp);
            app.setSellerName(appdata.optString("sellerName"));
            app.setSellerUrl(appdata.optString("sellerUrl"));
            // Dispositivos soportados
            JSONArray dispositivos = appdata.getJSONArray("supportedDevices");
            String[] dispositivosApp = new String[dispositivos.length()];
            for (int i = 0; i < dispositivos.length(); i++) {
                dispositivosApp[i] = dispositivos.getString(i);
            }
            app.setSupportedDevices(dispositivosApp);
            app.setTrackCensoredName(appdata.optString("trackCensoredName"));
            app.setTrackName(appdata.optString("trackName"));
            app.setTrackViewUrl(appdata.optString("trackViewUrl"));
            app.setVersion(appdata.optString("version"));

            return app;
        } catch (JSONException ex) {
            Logger.getLogger("com.panchosoft.itunes").log(Level.WARNING, "Error: " + ex.getMessage());
        }

        return null;
    }

From source file:com.joyfulmongo.db.QueryConditionFilterRelation.java

public static boolean isRelationQuery(JSONObject constraints) {
    Object obj = constraints.opt(S_KEY);
    return (obj != null);
}

From source file:org.jjdltc.cordova.plugin.sftp.JJsftp.java

/**
 * Validate if the options sent by user are not null or empty and also if accomplish the base structure
 * /*from w  ww .j a v a2  s.c o m*/
 * @param arguments         The arguments passed by user with the JSONObject that has the host options
 * @return                  A valid 'hostData' JSONObject with its inner host options to connect
 * @throws JSONException
 */
private JSONObject setHostData(JSONArray arguments) throws JSONException {
    JSONObject hostData = arguments.optJSONObject(0);
    boolean validArgs = true;
    String[] keys = new String[] { "host", "user", "pswd" };

    if (hostData == null) {
        return null;
    }
    if (hostData.opt("port") == null) {
        hostData.put("port", 22);
    }

    for (int i = 0; i < keys.length; i++) {
        if (hostData.opt(keys[i]) == null) {
            validArgs = false;
            break;
        }
    }

    return (validArgs) ? hostData : null;
}

From source file:org.jjdltc.cordova.plugin.sftp.JJsftp.java

/**
 * Validate if the options sent by user are not null or empty and also if accomplish the base structure
 * /*  w  ww .j a v a  2s.  co  m*/
 * @param arguments         The arguments passed by user with the JSONArray of JSONObject with the local and remote path of the files
 * @return                  A valid 'actionArr' JSONArray with its inner JSONObject paths
 */
private JSONArray setActionArr(JSONArray arguments) {
    JSONArray actionArr = arguments.optJSONArray(1);
    boolean validArr = true;

    if (actionArr == null) {
        return null;
    }

    for (int i = 0; i < actionArr.length(); i++) {
        JSONObject tempActionObj = actionArr.optJSONObject(i);
        if (tempActionObj == null) {
            validArr = false;
        } else {
            validArr = (tempActionObj.opt("remote") == null || tempActionObj.opt("local") == null) ? false
                    : validArr;
        }
        if (!validArr) {
            break;
        }
    }

    return (validArr) ? actionArr : null;
}

From source file:com.clover.sdk.v3.JsonHelper.java

public static Map toMap(JSONObject object) {
    Map map = new HashMap();
    Iterator keys = object.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        map.put(key, fromJson(object.opt(key)));
    }//www .  j  a  v  a 2 s  .c o m
    return map;
}

From source file:com.vk.sdkweb.api.model.ParseUtils.java

/**
 * Parses object with follow rules://w  w  w .  j  a va 2 s .c  o m
 *
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 *  arrays of primitive types, {@link java.lang.String}s and {@link com.vk.sdkweb.api.model.VKApiModel}s,
 *  list implementation line {@link com.vk.sdkweb.api.model.VKList}, {@link com.vk.sdkweb.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdkweb.api.model.VKPhotoSizes},
 *  {@link com.vk.sdkweb.api.model.VKApiModel}s.
 *
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T> type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings("rawtypes")
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:com.mirasense.scanditsdk.plugin.ScanditSDK.java

private void setOptionsOnBundle(JSONObject options, Bundle bundle) {
    @SuppressWarnings("unchecked")
    Iterator<String> iter = (Iterator<String>) options.keys();
    while (iter.hasNext()) {
        String key = iter.next();
        Object obj = options.opt(key);
        if (obj != null) {
            if (obj instanceof Float) {
                bundle.putFloat(key.toLowerCase(), (Float) obj);
            } else if (obj instanceof Double) {
                bundle.putDouble(key.toLowerCase(), (Double) obj);
            } else if (obj instanceof Integer) {
                bundle.putInt(key.toLowerCase(), (Integer) obj);
            } else if (obj instanceof Boolean) {
                bundle.putBoolean(key.toLowerCase(), (Boolean) obj);
            } else if (obj instanceof String) {
                bundle.putString(key.toLowerCase(), (String) obj);
            }/*  w  w  w.  j  a v a  2  s .  c om*/
        }
    }
}

From source file:org.boris.xlloop.http.JSONCodec.java

public static FunctionRequest decodeRequest(Reader r) throws IOException, JSONException {
    JSONTokener t = new JSONTokener(r);
    JSONObject jo = new JSONObject(t);
    String name = jo.getString("name");
    JSONArray args = jo.getJSONArray("args");
    String sheetName = (String) jo.opt("sheetName");
    JSONObject caller = (JSONObject) jo.opt("caller");
    XLSRef cref = null;//from www .j av a 2s.c  o m
    if (caller != null) {
        cref = (XLSRef) decode(caller);
    }
    XLoper[] xargs = new XLoper[args.length()];
    for (int i = 0; i < xargs.length; i++) {
        xargs[i] = decode(args.getJSONObject(i));
    }

    return new FunctionRequest(name, xargs, cref, sheetName);

}

From source file:com.jsonstore.api.JSONStoreCollection.java

/**
 * Count the number of documents in the collection that are based on the given query.
 * @param query//from w  w w  .  ja  v a  2 s. c  o m
 *             The find query that limits the count scope.
 * @param options
 *             Additional options to modify the count operation.
 * @return The total number of documents that are currently in the database that are not
 *         marked dirty and fit the find query.
 * @throws JSONStoreCountException
 *             A failure occurred when trying to determine the count.
 * @throws JSONStoreDatabaseClosedException
 *             The JSONStore database is closed, and cannot be accessed to
 *             perform the count.
 */
public int countDocuments(JSONStoreQueryParts query, JSONStoreCountOptions options)
        throws JSONStoreCountException, JSONStoreDatabaseClosedException {
    JSONStoreAnalyticsLogInstance logInst = JSONStoreLogger.startAnalyticsInstance(getUsername(), getName(),
            JSONStoreLogger.OPERATION_COUNT);

    try {
        getAccessor(); // This does some closed checks.
        if (query == null) {
            query = new JSONStoreQueryParts();
        }
        if (options == null)
            options = new JSONStoreCountOptions();

        JSONStoreFindOptions findOptions = new JSONStoreFindOptions();
        if (options.shouldIncludeDeletedDocuments()) {
            findOptions.includeDeletedDocuments(true);
        }

        findOptions.addSearchFilterSpecial(DatabaseConstants.SQL_COUNT);

        try {
            List<JSONObject> results = this.findDocuments(query, findOptions);

            if (results != null && results.size() == 1) {
                JSONObject countResults = results.get(0);
                if (countResults == null || countResults.opt(DatabaseConstants.SQL_COUNT) == null) {
                    throw new JSONStoreCountException(
                            "Could not count the results. Missing count return value internally");
                }

                return countResults.getInt(DatabaseConstants.SQL_COUNT);
            } else {
                throw new JSONStoreCountException(
                        "Could not count the results. Missing results from find internally");
            }
        } catch (JSONStoreFilterException e) {
            throw new JSONStoreCountException(
                    "Could not count the results. Filter exception occured internally", e);
        } catch (JSONStoreFindException e) {
            throw new JSONStoreCountException("Could not count the results. Find exception occured internally",
                    e);
        } catch (JSONException e) {
            throw new JSONStoreCountException("Could not count the results. JSONException occured internally",
                    e);

        }
    } finally {
        logInst.end();
    }
}