Example usage for org.json JSONObject optString

List of usage examples for org.json JSONObject optString

Introduction

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

Prototype

public String optString(String key) 

Source Link

Document

Get an optional string associated with a key.

Usage

From source file:com.google.blockly.model.BlockFactory.java

/** @return Number of blocks added to the factory. */
private int loadBlocks(InputStream blockIs) throws IOException {
    int blockAddedCount = 0;
    try {/*from  www .  j a v  a 2 s.c  om*/
        int size = blockIs.available();
        byte[] buffer = new byte[size];
        blockIs.read(buffer);

        String json = new String(buffer, "UTF-8");
        JSONArray blocks = new JSONArray(json);
        for (int i = 0; i < blocks.length(); i++) {
            JSONObject block = blocks.getJSONObject(i);
            String type = block.optString("type");
            if (!TextUtils.isEmpty(type)) {
                mBlockTemplates.put(type, fromJson(type, block));
                ++blockAddedCount;
            } else {
                throw new BlockLoadingException("Block " + i + " has no type and cannot be loaded.");
            }
        }
    } catch (JSONException e) {
        throw new BlockLoadingException(e);
    }

    return blockAddedCount;
}

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

public static ContainerObject getChildObject(String key, Object json) {
    ContainerObject result = null;// ww  w  .ja  v  a  2s  .c o m
    if (json instanceof JSONObject) {
        JSONObject childJson = (JSONObject) json;
        String type = childJson.optString(TypeProps.__type.toString());
        if (type == null || type.length() == 0) {
            String optype = childJson.optString(TypeProps.__op.toString());
            if (optype == null || optype.length() == 0) {
                result = null;
            } else {
                result = getOpCmd(key, optype, childJson);
            }
        } else {
            result = getTypedObject(key, type, childJson);
        }
    }

    return result;
}

From source file:de.luhmer.owncloudnewsreader.reader.owncloud.InsertFolderIntoDatabase.java

private static Folder parseFolder(JSONObject e) {
    return new Folder(e.optLong("id"), e.optString("name"));
}

From source file:com.util.finalProy.java

/**
 * @param args the command line arguments
 *///from w w w.jav a  2s .c  om
public static void main(String[] args) throws JSONException {
    // TODO code application logic her
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String jsonResult = sb.toString();
    System.out.println(sb.toString());
    System.out.println(
            "\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
    JSONObject objJason = new JSONObject(jsonResult);
    JSONArray dataJson = new JSONArray();
    dataJson = objJason.getJSONArray("data");

    System.out.println("objeto normal 1 " + dataJson.toString());
    //
    //
    System.out.println(
            "\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n");
    String jsonString2 = dataJson.toString();
    String temp = dataJson.toString();
    temp = jsonString2.replace("[", "");
    jsonString2 = temp.replace("]", "");
    System.out.println("new json string" + jsonString2);

    JSONObject objJson2 = new JSONObject(jsonString2);
    System.out.println("el objeto simple json es " + objJson2.toString());

    System.out.println(
            "\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n");

    String account1 = objJson2.optString("account");
    System.out.println(account1);
    JSONObject objJson3 = new JSONObject(account1);
    System.out.println("el ULTIMO OBJETO SIMPLE ES  " + objJson3.toString());
    System.out.println(
            "\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n");
    String firstName = objJson3.getString("first_name");
    System.out.println(firstName);
    System.out.println(objJson3.get("id"));
    System.out.println(
            "\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n");
    Gson gson = new Gson();
    Account account = gson.fromJson(objJson3.toString(), Account.class);
    System.out.println(account.getFirst_name());
    System.out.println(account.getCreation());
}

From source file:org.sufficientlysecure.privacybox.VaultProvider.java

/**
 * Include metadata for a document in the given result cursor.
 *///from w  ww.  j a  va2 s  . com
private void includeDocument(MatrixCursor result, long docId) throws IOException, GeneralSecurityException {
    final EncryptedDocument doc = getDocument(docId);
    if (!doc.getFile().exists()) {
        throw new FileNotFoundException("Missing document " + docId);
    }

    final JSONObject meta = doc.readMetadata();

    int flags = 0;

    final String mimeType = meta.optString(Document.COLUMN_MIME_TYPE);
    if (Document.MIME_TYPE_DIR.equals(mimeType)) {
        flags |= Document.FLAG_DIR_SUPPORTS_CREATE;
    } else {
        flags |= Document.FLAG_SUPPORTS_WRITE;
    }
    flags |= Document.FLAG_SUPPORTS_DELETE;

    final RowBuilder row = result.newRow();
    row.add(Document.COLUMN_DOCUMENT_ID, meta.optLong(Document.COLUMN_DOCUMENT_ID));
    row.add(Document.COLUMN_DISPLAY_NAME, meta.optString(Document.COLUMN_DISPLAY_NAME));
    row.add(Document.COLUMN_SIZE, meta.optLong(Document.COLUMN_SIZE));
    row.add(Document.COLUMN_MIME_TYPE, mimeType);
    row.add(Document.COLUMN_FLAGS, flags);
    row.add(Document.COLUMN_LAST_MODIFIED, meta.optLong(Document.COLUMN_LAST_MODIFIED));
}

From source file:org.eclipse.orion.server.core.tasks.TaskInfo.java

/**
 * Returns a task object based on its JSON representation. Returns
 * null if the given string is not a valid JSON task representation.
 * This function does not set <code>canBeCanceled</code>. The caller
 * must find out himself if the task can be canceled and set this flag.
 * @throws CorruptedTaskException //from  w w  w.j a  va 2s .co m
 */
public static TaskInfo fromJSON(TaskDescription description, String taskString) throws CorruptedTaskException {
    TaskInfo info;
    try {
        JSONObject json = new JSONObject(taskString);
        info = new TaskInfo(description.getUserId(), description.getTaskId(), description.isKeep());
        if (json.has(KEY_EXPIRES))
            info.expires = new Date(json.getLong(KEY_EXPIRES));

        if (json.has(KEY_TIMESTAMP))
            info.timestamp = new Date(json.getLong(KEY_TIMESTAMP));

        info.lengthComputable = json.optBoolean(KEY_LENGTH_COMPUTABLE);
        if (json.has(KEY_LOADED))
            info.loaded = json.optInt(KEY_LOADED);
        if (json.has(KEY_TOTAL))
            info.total = json.getInt(KEY_TOTAL);

        if (json.has(KEY_TYPE))
            info.status = TaskStatus.fromString(json.optString(KEY_TYPE));

        if (json.has(KEY_RESULT))
            info.result = ServerStatus.fromJSON(json.optString(KEY_RESULT));
        if (json.has(KEY_LOCATION_ONLY)) {
            info.locationOnly = json.optBoolean(KEY_LOCATION_ONLY);
        }

        return info;
    } catch (JSONException e) {
        throw new CorruptedTaskException(taskString, e);
    }
}

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

public iTunesApp[] buscarApp(String appName, int limit) {
        // Hacemos una bsqueda en iTunes
        String datos_json = buscarDatosAppJSON(appName, 15);

        if (datos_json == null || datos_json.length() == 0) {
            return null;
        }/* w ww.  j  a va 2s .com*/

        try {
            JSONObject ob = new JSONObject(datos_json);

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

            int totalResultados = ob.getInt("resultCount");
            if (totalResultados == 0) {
                return null;
            }

            iTunesApp[] appsencontradas = new iTunesApp[totalResultados];

            for (int c = 0; c < totalResultados; c++) {
                JSONArray resultados = ob.getJSONArray("results");

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

                JSONObject appdata = resultados.getJSONObject(c);

                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"));

                appsencontradas[c] = app;

            }
            return appsencontradas;
        } 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 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 ww .j  a va  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:info.papdt.blacklight.support.Utility.java

public static String getSplash() {
    String splash = "";
    try {//ww  w.java2 s  . co m
        WeiboParameters params = new WeiboParameters();
        params.put("app", "bl");
        String json = HttpUtility.doRequest(Constants.SPLASHES_API, params, HttpUtility.GET);
        JSONObject jsonObj = new JSONObject(json);
        splash = jsonObj.optString("content");
    } catch (Exception e) {
        Log.e(TAG, "Failed to get splash, bad luck.", e);
    }
    return splash;
}