Example usage for org.json JSONObject has

List of usage examples for org.json JSONObject has

Introduction

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

Prototype

public boolean has(String key) 

Source Link

Document

Determine if the JSONObject contains a specific key.

Usage

From source file:org.chromium.ChromeStorage.java

private JSONObject getStoredValuesForKeys(CordovaArgs args, boolean useDefaultValues) {
    JSONObject ret = new JSONObject();
    try {/*from w  w w. j  a  v  a2  s.co m*/
        String namespace = args.getString(0);
        JSONObject jsonObject = (JSONObject) args.optJSONObject(1);
        JSONArray jsonArray = args.optJSONArray(1);
        boolean isNull = args.isNull(1);
        List<String> keys = new ArrayList<String>();

        if (jsonObject != null) {
            keys = toStringList(jsonObject.names());
            // Ensure default values of keys are maintained
            if (useDefaultValues) {
                ret = jsonObject;
            }
        } else if (jsonArray != null) {
            keys = toStringList(jsonArray);
        } else if (isNull) {
            keys = null;
        }

        if (keys != null && keys.isEmpty()) {
            ret = new JSONObject();
        } else {
            JSONObject storage = getStorage(namespace);

            if (keys == null) {
                // return the whole storage if the key given is null
                ret = storage;
            } else {
                // return the storage for the keys specified
                for (String key : keys) {
                    if (storage.has(key)) {
                        Object value = storage.get(key);
                        ret.put(key, value);
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Storage is corrupted!", e);
        ret = null;
    } catch (IOException e) {
        Log.e(LOG_TAG, "Could not retrieve storage", e);
        ret = null;
    }

    return ret;
}

From source file:de.hackerspacebremen.format.JSONFormatter.java

@Override
public T reformat(final String object, final Class<T> entityClass) throws FormatException {
    T result = null;/*from w  w  w . j  a v  a2  s  .  c o m*/
    final Map<String, Field> fieldMap = new HashMap<String, Field>();
    if (entityClass.isAnnotationPresent(Entity.class)) {
        final Field[] fields = entityClass.getDeclaredFields();
        for (final Field field : fields) {
            if (field.isAnnotationPresent(FormatPart.class)) {
                fieldMap.put(field.getAnnotation(FormatPart.class).key(), field);
            }
        }
        try {
            final JSONObject json = new JSONObject(object);
            result = entityClass.newInstance();
            for (final String key : fieldMap.keySet()) {
                if (json.has(key)) {
                    final Field field = fieldMap.get(key);
                    final Method method = entityClass.getMethod(this.getSetter(field.getName()),
                            new Class<?>[] { field.getType() });

                    final String type = field.getType().toString();
                    if (type.equals("class com.google.appengine.api.datastore.Key")) {
                        method.invoke(result, KeyFactory.stringToKey(json.getString(key)));
                    } else if (type.equals("class com.google.appengine.api.datastore.Text")) {
                        method.invoke(result, new Text(json.getString(key)));
                    } else if (type.equals("boolean")) {
                        method.invoke(result, json.getBoolean(key));
                    } else if (type.equals("long")) {
                        method.invoke(result, json.getLong(key));
                    } else if (type.equals("int")) {
                        method.invoke(result, json.getInt(key));
                    } else {
                        method.invoke(result, json.get(key));
                    }
                }
            }
        } catch (JSONException e) {
            logger.warning("JSONException occured: " + e.getMessage());
            throw new FormatException();
        } catch (NoSuchMethodException e) {
            logger.warning("NoSuchMethodException occured: " + e.getMessage());
            throw new FormatException();
        } catch (SecurityException e) {
            logger.warning("SecurityException occured: " + e.getMessage());
            throw new FormatException();
        } catch (IllegalAccessException e) {
            logger.warning("IllegalAccessException occured: " + e.getMessage());
            throw new FormatException();
        } catch (IllegalArgumentException e) {
            logger.warning("IllegalArgumentException occured: " + e.getMessage());
            throw new FormatException();
        } catch (InvocationTargetException e) {
            logger.warning("InvocationTargetException occured: " + e.getMessage());
            throw new FormatException();
        } catch (InstantiationException e) {
            logger.warning("InstantiationException occured: " + e.getMessage());
            throw new FormatException();
        }
    }
    return result;
}

From source file:com.github.sgelb.booket.SearchResultActivity.java

private void processResult(String result) {
    JSONArray items = null;/*  w w w  .  ja  v a 2  s .  c  o  m*/
    try {
        JSONObject jsonObject = new JSONObject(result);
        items = jsonObject.getJSONArray("items");
    } catch (JSONException e) {
        noResults.setVisibility(View.VISIBLE);
        return;
    }

    try {

        // iterate over items aka books
        Log.d("R2R", "Items: " + items.length());
        for (int i = 0; i < items.length(); i++) {
            Log.d("R2R", "\nBook " + (i + 1));
            JSONObject item = (JSONObject) items.get(i);
            JSONObject info = item.getJSONObject("volumeInfo");
            Book book = new Book();

            // add authors
            String authors = "";
            if (info.has("authors")) {
                JSONArray jAuthors = info.getJSONArray("authors");
                for (int j = 0; j < jAuthors.length() - 1; j++) {
                    authors += jAuthors.getString(j) + ", ";
                }
                authors += jAuthors.getString(jAuthors.length() - 1);
            } else {
                authors = "n/a";
            }
            book.setAuthors(authors);
            Log.d("R2R", "authors " + book.getAuthors());

            // add title
            if (info.has("title")) {
                book.setTitle(info.getString("title"));
                Log.d("R2R", "title " + book.getTitle());
            }

            // add pageCount
            if (info.has("pageCount")) {
                book.setPageCount(info.getInt("pageCount"));
                Log.d("R2R", "pageCount " + book.getPageCount());
            }

            // add publisher
            if (info.has("publisher")) {
                book.setPublisher(info.getString("publisher"));
                Log.d("R2R", "publisher " + book.getPublisher());
            }

            // add description
            if (info.has("description")) {
                book.setDescription(info.getString("description"));
                Log.d("R2R", "description " + book.getDescription());
            }

            // add isbn
            if (info.has("industryIdentifiers")) {
                JSONArray ids = info.getJSONArray("industryIdentifiers");
                for (int k = 0; k < ids.length(); k++) {
                    JSONObject id = ids.getJSONObject(k);
                    if (id.getString("type").equalsIgnoreCase("ISBN_13")) {
                        book.setIsbn(id.getString("identifier"));
                        break;
                    }
                    if (id.getString("type").equalsIgnoreCase("ISBN_10")) {
                        book.setIsbn(id.getString("identifier"));
                    }
                }
                Log.d("R2R", "isbn " + book.getIsbn());
            }

            // add published date
            if (info.has("publishedDate")) {
                book.setYear(info.getString("publishedDate").substring(0, 4));
                Log.d("R2R", "publishedDate " + book.getYear());
            }

            // add cover thumbnail
            book.setThumbnailBitmap(defaultThumbnail);

            if (info.has("imageLinks")) {
                // get cover url from google
                JSONObject imageLinks = info.getJSONObject("imageLinks");
                if (imageLinks.has("thumbnail")) {
                    book.setThumbnailUrl(imageLinks.getString("thumbnail"));
                }
            } else if (book.getIsbn() != null) {
                // get cover url from amazon
                String amazonCoverUrl = "http://ecx.images-amazon.com/images/P/" + isbn13to10(book.getIsbn())
                        + ".01._SCMZZZZZZZ_.jpg";
                book.setThumbnailUrl(amazonCoverUrl);
            }

            // download cover thumbnail
            if (book.getThumbnailUrl() != null && !book.getThumbnailUrl().isEmpty()) {
                new DownloadThumbNail(book).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                        book.getThumbnailUrl());
                Log.d("R2R", "thumbnail " + book.getThumbnailUrl());
            }

            // add google book id
            if (item.has("id")) {
                book.setGoogleId(item.getString("id"));
            }

            bookList.add(book);

        }
    } catch (Exception e) {
        Log.d("R2R", "Exception: " + e.toString());
        // FIXME: catch exception
    }
}

From source file:eu.inmite.apps.smsjizdenka.service.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent == null) {
        return;//ww  w.j  ava  2  s  . c o m
    }
    final boolean force = intent.getBooleanExtra("force", false);
    try {
        Locale loc = Locale.getDefault();
        String lang = loc.getISO3Language(); // http://www.loc.gov/standards/iso639-2/php/code_list.php; T-values if present both T and B
        if (lang == null || lang.length() == 0) {
            lang = "";
        }

        int serverVersion = intent.getIntExtra("serverVersion", -1);
        boolean fromPush = serverVersion != -1;
        JSONObject versionJson = null;
        if (!fromPush) {
            versionJson = getVersion(true);
            serverVersion = versionJson.getInt("version");
        }
        int localVersion = Preferences.getInt(c, Preferences.DATA_VERSION, -1);
        final String localLanguage = Preferences.getString(c, Preferences.DATA_LANGUAGE, "");

        if (serverVersion <= localVersion && !force && lang.equals(localLanguage)
                && !LOCAL_DEFINITION_TESTING) {
            // don't update
            DebugLog.i("Nothing new, not updating");
            return;
        }

        // update but don't notify about it.
        boolean firstLaunchNoUpdate = ((localVersion == -1
                && getVersion(false).getInt("version") == serverVersion) || !lang.equals(localLanguage));

        if (!firstLaunchNoUpdate) {
            DebugLog.i("There are new definitions available!");
        }

        handleAuthorMessage(versionJson, lang, intent, fromPush);

        InputStream is = getIS(URL_TICKETS_ID);
        try {
            String json = readResult(is);

            JSONObject o = new JSONObject(json);
            JSONArray array = o.getJSONArray("tickets");

            final SQLiteDatabase db = DatabaseHelper.get(this).getWritableDatabase();
            for (int i = 0; i < array.length(); i++) {
                final JSONObject city = array.getJSONObject(i);
                try {

                    final ContentValues cv = new ContentValues();
                    cv.put(Cities._ID, city.getInt("id"));
                    cv.put(Cities.CITY, getStringLocValue(city, lang, "city"));
                    if (city.has("city_pubtran")) {
                        cv.put(Cities.CITY_PUBTRAN, city.getString("city_pubtran"));
                    }
                    cv.put(Cities.COUNTRY, city.getString("country"));
                    cv.put(Cities.CURRENCY, city.getString("currency"));
                    cv.put(Cities.DATE_FORMAT, city.getString("dateFormat"));
                    cv.put(Cities.IDENTIFICATION, city.getString("identification"));
                    cv.put(Cities.LAT, city.getDouble("lat"));
                    cv.put(Cities.LON, city.getDouble("lon"));
                    cv.put(Cities.NOTE, getStringLocValue(city, lang, "note"));
                    cv.put(Cities.NUMBER, city.getString("number"));
                    cv.put(Cities.P_DATE_FROM, city.getString("pDateFrom"));
                    cv.put(Cities.P_DATE_TO, city.getString("pDateTo"));
                    cv.put(Cities.P_HASH, city.getString("pHash"));
                    cv.put(Cities.PRICE, city.getString("price"));
                    cv.put(Cities.PRICE_NOTE, getStringLocValue(city, lang, "priceNote"));
                    cv.put(Cities.REQUEST, city.getString("request"));
                    cv.put(Cities.VALIDITY, city.getInt("validity"));
                    if (city.has("confirmReq")) {
                        cv.put(Cities.CONFIRM_REQ, city.getString("confirmReq"));
                    }
                    if (city.has("confirm")) {
                        cv.put(Cities.CONFIRM, city.getString("confirm"));
                    }

                    final JSONArray additionalNumbers = city.getJSONArray("additionalNumbers");
                    for (int j = 0; j < additionalNumbers.length() && j < 3; j++) {
                        cv.put("ADDITIONAL_NUMBER_" + (j + 1), additionalNumbers.getString(j));
                    }

                    db.beginTransaction();
                    int count = db.update(DatabaseHelper.CITY_TABLE_NAME, cv,
                            Cities._ID + " = " + cv.getAsInteger(Cities._ID), null);
                    if (count == 0) {
                        db.insert(DatabaseHelper.CITY_TABLE_NAME, null, cv);
                    }

                    db.setTransactionSuccessful();
                    getContentResolver().notifyChange(Cities.CONTENT_URI, null);
                } finally {
                    if (db.inTransaction()) {
                        db.endTransaction();
                    }
                }
            }
            Preferences.set(c, Preferences.DATA_VERSION, serverVersion);
            Preferences.set(c, Preferences.DATA_LANGUAGE, lang);
            if (!firstLaunchNoUpdate && !fromPush) {
                final int finalServerVersion = serverVersion;
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(UpdateService.this,
                                getString(R.string.cities_update_completed, finalServerVersion),
                                Toast.LENGTH_LONG).show();
                    }
                });
            }
            if (LOCAL_DEFINITION_TESTING) {
                DebugLog.w(
                        "Local definition testing - data updated from assets - must be removed in production!");
            }
        } finally {
            is.close();
        }
    } catch (IOException e) {
        DebugLog.e("IOException when calling update: " + e.getMessage(), e);
    } catch (JSONException e) {
        DebugLog.e("JSONException when calling update: " + e.getMessage(), e);
    }
}

From source file:eu.inmite.apps.smsjizdenka.service.UpdateService.java

private String getStringLocValue(JSONObject json, String lang, String key) {
    String value = "";

    try {/*from   www . jav a  2  s .com*/
        if (json.has(key + "_" + lang)) {
            value = json.getString(key + "_" + lang);
        } else {
            value = json.getString(key);
        }
    } catch (JSONException je) {
        // failed
    }

    return value;
}

From source file:com.goliathonline.android.kegbot.io.RemoteKegHandler.java

/** {@inheritDoc} */
@Override/*  w ww. j  a  v  a 2 s . c  o m*/
public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver)
        throws JSONException, IOException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    // Walk document, parsing any incoming entries
    JSONObject result = parser.getJSONObject("result");
    JSONObject keg = result.getJSONObject("keg");
    JSONObject type = result.getJSONObject("type");
    JSONObject image = type.getJSONObject("image");

    final String kegId = sanitizeId(keg.getString("id"));
    final Uri kegUri = Kegs.buildKegUri(kegId);

    // Check for existing details, only update when changed
    final ContentValues values = queryKegDetails(kegUri, resolver);
    final long localUpdated = values.getAsLong(SyncColumns.UPDATED);
    final long serverUpdated = 500; //entry.getUpdated();
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "found keg " + kegId);
        Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated);
    }

    // Clear any existing values for this session, treating the
    // incoming details as authoritative.
    batch.add(ContentProviderOperation.newDelete(kegUri).build());

    final ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(Kegs.CONTENT_URI);

    builder.withValue(SyncColumns.UPDATED, serverUpdated);
    builder.withValue(Kegs.KEG_ID, kegId);

    // Inherit starred value from previous row
    if (values.containsKey(Kegs.KEG_STARRED)) {
        builder.withValue(Kegs.KEG_STARRED, values.getAsInteger(Kegs.KEG_STARRED));
    }

    if (keg.has("status"))
        builder.withValue(Kegs.STATUS, keg.getString("status"));

    if (keg.has("volume_ml_remain"))
        builder.withValue(Kegs.VOLUME_REMAIN, keg.getDouble("volume_ml_remain"));

    if (keg.has("description"))
        builder.withValue(Kegs.DESCRIPTION, keg.getString("description"));

    if (keg.has("type_id"))
        builder.withValue(Kegs.TYPE_ID, keg.getString("type_id"));

    if (keg.has("size_id"))
        builder.withValue(Kegs.SIZE_ID, keg.getInt("size_id"));

    if (keg.has("percent_full"))
        builder.withValue(Kegs.PERCENT_FULL, keg.getDouble("percent_full"));

    if (keg.has("size_name"))
        builder.withValue(Kegs.SIZE_NAME, keg.getString("size_name"));

    if (keg.has("spilled_ml"))
        builder.withValue(Kegs.VOLUME_SPILL, keg.getDouble("spilled_ml"));

    if (keg.has("size_volume_ml"))
        builder.withValue(Kegs.VOLUME_SIZE, keg.getDouble("size_volume_ml"));

    if (type.has("name"))
        builder.withValue(Kegs.KEG_NAME, type.getString("name"));

    if (type.has("abv"))
        builder.withValue(Kegs.KEG_ABV, type.getDouble("abv"));

    if (image.has("url"))
        builder.withValue(Kegs.IMAGE_URL, image.getString("url"));

    // Normal keg details ready, write to provider
    batch.add(builder.build());

    return batch;
}

From source file:org.hubiquitus.twitter4j_1_1.stream.HStream.java

public void fireEvent(JSONObject item) {
    int code = item.has("text") ? 1
            : item.has("warning") ? 2
                    : item.has("delete") ? 3
                            : item.has("scrub_geo") ? 4
                                    : item.has("limit") ? 5
                                            : item.has("status_withheld") ? 6
                                                    : item.has("user_withheld") ? 7
                                                            : item.has("disconnect") ? 8 : 0;

    for (HStreamListner listener : listeners) {
        switch (code) {
        case 1:// w  w  w . ja  va2 s .  c  o  m
            listener.onStatus(item);
            break;
        case 2:
            listener.onStallWarning(item);
            break;
        case 3:
            listener.onLocationDeletionNotices(item);
            break;
        case 4:
            listener.onLimitNotices(item);
            break;
        case 5:
            listener.onStatusDeletionNotices(item);
            break;
        case 6:
            listener.onStatusWithheld(item);
            break;
        case 7:
            listener.onUserWithheld(item);
            break;
        case 8:
            listener.onDisconnectMessages(item);
            break;
        default:
            listener.onOtherMessage(item);
        }
    }

    if (code == 8) {
        try {
            displayLogMessage(item.getJSONObject("disconnect").getInt("code"));
        } catch (JSONException e) {
            log.error("can not fetch the error code for disconnection", e);
        }
        stop();
        loop = new Loop(this);
        loop.owner.start();
    }

}

From source file:com.basetechnology.s0.agentserver.field.BooleanField.java

public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) {
    String type = fieldJson.optString("type");
    if (type == null || !(type.equals("option") || type.equals("boolean")))
        return null;
    String name = fieldJson.has("name") ? fieldJson.optString("name") : null;
    String label = fieldJson.has("label") ? fieldJson.optString("label") : null;
    String description = fieldJson.has("description") ? fieldJson.optString("description") : null;
    boolean defaultValue = fieldJson.has("default_value") ? fieldJson.optBoolean("default_value") : true;
    String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null;
    return new BooleanField(symbolTable, name, label, description, defaultValue, compute);
}

From source file:com.deltachi.videotex.grabers.YIFYGraber.java

private Object[][] getLatestTorrentsWithDetails(int set, int limit)
        throws JSONException, IOException, MalformedURLException, NoSuchAlgorithmException {
    Object[][] o = new Object[limit][2];
    JSONReader jsonReader = new JSONReader();
    JSONObject jSONObject = null;
    jSONObject = jsonReader.readJsonFromUrl(
            "http://ytsre.eu/api/list.json?set=" + Integer.toString(set) + "&limit=" + Integer.toString(limit));
    if (jSONObject.has("status")) {
        if (jSONObject.get("status").equals("fail")) {
            o = null;/*from   w w  w  .  j  a  v  a  2  s .c o m*/
        }
    } else {
        JSONArray jSONArray = (JSONArray) jSONObject.get("MovieList");
        for (int i = 0; i < jSONArray.length(); i++) {
            JSONObject jsono = (JSONObject) jSONArray.get(i);
            int torrentID = Integer.parseInt(jsono.get("MovieID").toString());
            String imdbCode = jsono.get("ImdbCode").toString();
            o[i][0] = getTorrentDetails(torrentID);
            o[i][1] = imdbCode;
        }
    }
    return o;
}

From source file:com.deltachi.videotex.grabers.YIFYGraber.java

private Torrent getTorrentDetails(int id)
        throws NoSuchAlgorithmException, MalformedURLException, JSONException, IOException {
    Torrent torrent;//from   w ww .j a v a2 s. com
    JSONReader jsonReader = new JSONReader();
    JSONObject jSONObject = null;
    jSONObject = jsonReader.readJsonFromUrl("http://ytsre.eu/api/movie.json?id=" + Integer.toString(id));
    torrent = new Torrent();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    try {
        torrent.setDateUploaded(dateFormat.parse(jSONObject.get("DateUploaded").toString()));
    } catch (ParseException ex) {
        Logger.getLogger(YIFYGraber.class.getName()).log(Level.SEVERE, null, ex);
    }
    torrent.setQuality(jSONObject.get("Quality").toString());
    torrent.setSize(jSONObject.get("Size").toString());
    torrent.setTorrentSeeds(Integer.parseInt(jSONObject.get("TorrentSeeds").toString()));
    torrent.setTorrentPeers(Integer.parseInt(jSONObject.get("TorrentPeers").toString()));
    torrent.setMagnetURL(jSONObject.get("TorrentMagnetUrl").toString());
    URL torrentUrl = null;
    torrentUrl = new URL(jSONObject.get("TorrentUrl").toString());
    byte[] torrentFile = null;
    torrentFile = Downloader.getAsByteArray(torrentUrl);
    torrent.setTorrentFile(torrentFile);
    String checksum = "";
    checksum = Downloader.SHAsum(torrentFile);
    Collection<Screenshot> screenshotCollection = new ArrayList<>();
    int k = 1;
    while (true) {
        URL screenshotURL = null;
        if (jSONObject.has("MediumScreenshot" + Integer.toString(k))) {
            screenshotURL = new URL(jSONObject.get("MediumScreenshot" + Integer.toString(k)).toString());
        } else {
            break;
        }
        byte[] screenshotFile = null;
        screenshotFile = Downloader.getAsByteArray(screenshotURL);
        Screenshot screenshot = new Screenshot();
        screenshot.setTorrentID(torrent);
        screenshot.setPicture(screenshotFile);
        screenshotCollection.add(screenshot);
        k++;
    }
    torrent.setScreenshotCollection(screenshotCollection);
    torrent.setChecksum(checksum);
    torrent.setDistributor("yify");
    return torrent;
}