Example usage for org.json JSONObject optJSONArray

List of usage examples for org.json JSONObject optJSONArray

Introduction

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

Prototype

public JSONArray optJSONArray(String key) 

Source Link

Document

Get an optional JSONArray associated with a key.

Usage

From source file:net.algart.simagis.live.json.minimal.SimagisLiveUtils.java

public static JSONArray openArray(JSONObject object, String key) {
    JSONArray result;/*w w w  .j  ava  2  s  . c  om*/
    try {
        result = object.optJSONArray(key);
        if (result == null) {
            result = new JSONArray();
            object.put(key, result);
        }
    } catch (JSONException e) {
        throw new AssertionError(e);
    }
    return result;
}

From source file:com.mparticle.internal.ConfigManager.java

/**
 * The is called on startup. The only thing that's completely necessary is that we fire up kits.
 *//*from w w w .  ja v  a 2 s . c o m*/
public JSONArray getLatestKitConfiguration() {
    String oldConfig = mPreferences.getString(CONFIG_JSON, null);
    if (!MPUtility.isEmpty(oldConfig)) {
        try {
            JSONObject oldConfigJson = new JSONObject(oldConfig);
            return oldConfigJson.optJSONArray(KEY_EMBEDDED_KITS);
        } catch (Exception jse) {

        }
    }
    return null;
}

From source file:com.mparticle.internal.ConfigManager.java

public synchronized void updateConfig(JSONObject responseJSON, boolean persistJson) throws JSONException {
    SharedPreferences.Editor editor = mPreferences.edit();
    if (persistJson) {
        saveConfigJson(responseJSON);//from  ww  w.j a  v  a 2s .co  m
    }

    if (responseJSON.has(KEY_UNHANDLED_EXCEPTIONS)) {
        mLogUnhandledExceptions = responseJSON.getString(KEY_UNHANDLED_EXCEPTIONS);
    }

    if (responseJSON.has(KEY_PUSH_MESSAGES)) {
        sPushKeys = responseJSON.getJSONArray(KEY_PUSH_MESSAGES);
        editor.putString(KEY_PUSH_MESSAGES, sPushKeys.toString());
    }

    mRampValue = responseJSON.optInt(KEY_RAMP, -1);

    if (responseJSON.has(KEY_OPT_OUT)) {
        mSendOoEvents = responseJSON.getBoolean(KEY_OPT_OUT);
    } else {
        mSendOoEvents = false;
    }

    if (responseJSON.has(ProviderPersistence.KEY_PERSISTENCE)) {
        setProviderPersistence(new ProviderPersistence(responseJSON, mContext));
    } else {
        setProviderPersistence(null);
    }

    mSessionTimeoutInterval = responseJSON.optInt(KEY_SESSION_TIMEOUT, -1);
    mUploadInterval = responseJSON.optInt(KEY_UPLOAD_INTERVAL, -1);

    mTriggerMessageMatches = null;
    mTriggerMessageHashes = null;
    if (responseJSON.has(KEY_TRIGGER_ITEMS)) {
        try {
            JSONObject items = responseJSON.getJSONObject(KEY_TRIGGER_ITEMS);
            if (items.has(KEY_MESSAGE_MATCHES)) {
                mTriggerMessageMatches = items.getJSONArray(KEY_MESSAGE_MATCHES);
            }
            if (items.has(KEY_TRIGGER_ITEM_HASHES)) {
                mTriggerMessageHashes = items.getJSONArray(KEY_TRIGGER_ITEM_HASHES);
            }
        } catch (JSONException jse) {

        }

    }

    if (responseJSON.has(KEY_INFLUENCE_OPEN)) {
        mInfluenceOpenTimeout = responseJSON.getLong(KEY_INFLUENCE_OPEN) * 60 * 1000;
    } else {
        mInfluenceOpenTimeout = 30 * 60 * 1000;
    }

    mRestrictAAIDfromLAT = responseJSON.optBoolean(KEY_AAID_LAT, true);
    mIncludeSessionHistory = responseJSON.optBoolean(KEY_INCLUDE_SESSION_HISTORY, true);
    if (responseJSON.has(KEY_DEVICE_PERFORMANCE_METRICS_DISABLED)) {
        MParticle.setDevicePerformanceMetricsDisabled(
                responseJSON.optBoolean(KEY_DEVICE_PERFORMANCE_METRICS_DISABLED, false));
    }

    editor.apply();
    applyConfig();

    MParticle.getInstance().getKitManager().updateKits(responseJSON.optJSONArray(KEY_EMBEDDED_KITS));
}

From source file:de.hscoburg.etif.vbis.lagerix.android.barcode.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException {

    CharSequence contents = HttpHelper.downloadViaHttp(
            "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;/*from   w  w  w  .  j  a v a 2s  . com*/
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>(authorsArray.length());
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e.toString());
    }

    Collection<String> newTexts = new ArrayList<String>();
    maybeAddText(title, newTexts);
    maybeAddTextSeries(authors, newTexts);
    maybeAddText(pages == null || pages.length() == 0 ? null : pages + "pp.", newTexts);

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}

From source file:org.catnut.fragment.UserTimelineFragment.java

private void loadFromCloud(long max_id) {
    mSwipeRefreshLayout.setRefreshing(true);
    CatnutAPI api = TweetAPI.userTimeline(mScreenName, 0, max_id, getFetchSize(), 0, 0, 0, 0);
    mRequestQueue.add(new CatnutRequest(getActivity(), api,
            new StatusProcessor.TimelineProcessor(Status.OTHERS, false), new Response.Listener<JSONObject>() {
                @Override/*from   w w w  .  j  ava2  s .com*/
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "load more from cloud done...");
                    mTotal = response.optInt(TOTAL_NUMBER);
                    int newSize = response.optJSONArray(Status.MULTIPLE).length() + mAdapter.getCount();
                    Bundle args = new Bundle();
                    args.putInt(TAG, newSize);
                    getLoaderManager().restartLoader(0, args, UserTimelineFragment.this);
                }
            }, errorListener)).setTag(TAG);
}

From source file:org.catnut.fragment.UserTimelineFragment.java

@Override
protected void refresh() {
    // ???//w w  w.j  a  va2s . co m
    if (!isNetworkAvailable()) {
        Toast.makeText(getActivity(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
        initFromLocal();
        return;
    }
    // refresh!
    final int size = getFetchSize();
    (new Thread(new Runnable() {
        @Override
        public void run() {
            // ??????(?-)???Orz...
            String query = CatnutUtils.buildQuery(new String[] { BaseColumns._ID }, mSelection, Status.TABLE,
                    null, BaseColumns._ID + " desc", size + ", 1" // limit x, y
            );
            Cursor cursor = getActivity().getContentResolver().query(CatnutProvider.parse(Status.MULTIPLE),
                    null, query, null, null);
            // the cursor never null?
            final long since_id;
            if (cursor.moveToNext()) {
                since_id = cursor.getLong(0);
            } else {
                since_id = 0;
            }
            cursor.close();
            final CatnutAPI api = TweetAPI.userTimeline(mScreenName, since_id, 0, getFetchSize(), 0, 0, 0, 0);
            // refresh...
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mRequestQueue.add(new CatnutRequest(getActivity(), api,
                            new StatusProcessor.TimelineProcessor(Status.OTHERS, true),
                            new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    Log.d(TAG, "refresh done...");
                                    mTotal = response.optInt(TOTAL_NUMBER);
                                    // ???
                                    JSONArray jsonArray = response.optJSONArray(Status.MULTIPLE);
                                    int newSize = jsonArray.length(); // ...
                                    Bundle args = new Bundle();
                                    args.putInt(TAG, newSize);
                                    getLoaderManager().restartLoader(0, args, UserTimelineFragment.this);
                                }
                            }, errorListener)).setTag(TAG);
                }
            });
        }
    })).start();
}

From source file:com.commonsware.empub.BookContents.java

BookContents(JSONObject raw) {
    this.raw = raw;
    chapters = raw.optJSONArray("chapters");

    for (int i = 0; i < getChapterCount(); i++) {
        files.put(getChapterFile(i), i);
    }/*from  w w  w .  j a v a 2  s . c  o  m*/
}

From source file:org.catnut.metadata.Status.java

@Override
public ContentValues convert(JSONObject json) {
    ContentValues tweet = new ContentValues();
    tweet.put(BaseColumns._ID, json.optLong(Constants.ID));
    tweet.put(created_at, json.optString(created_at));
    // ?jsonsql???
    tweet.put(columnText, json.optString(text));
    tweet.put(source, json.optString(source));
    tweet.put(favorited, json.optBoolean(favorited));
    tweet.put(truncated, json.optBoolean(truncated));
    // ??????/*from  w  ww. ja v a 2s.  c  o  m*/
    JSONArray thumbs = json.optJSONArray(pic_urls);
    if (thumbs != null) {
        // json
        tweet.put(pic_urls, thumbs.toString());
    }
    tweet.put(thumbnail_pic, json.optString(thumbnail_pic));
    tweet.put(bmiddle_pic, json.optString(bmiddle_pic));
    tweet.put(original_pic, json.optString(original_pic));
    // ???
    if (json.has(retweeted_status)) {
        tweet.put(retweeted_status, json.optJSONObject(retweeted_status).toString());
    }
    // 
    if (json.has(User.SINGLE)) {
        tweet.put(uid, json.optJSONObject(User.SINGLE).optLong(Constants.ID));
    } else if (json.has(uid)) {
        tweet.put(uid, json.optLong(uid));
    }
    tweet.put(reposts_count, json.optInt(reposts_count));
    tweet.put(comments_count, json.optInt(comments_count));
    tweet.put(attitudes_count, json.optInt(attitudes_count));
    return tweet;
}

From source file:com.facebook.android.friendsmash.integration.GraphAPICall.java

/**
 * Helper method to extract JSONArray with data returned in GraphResponse.
 * Useful for example for extracting friends data returned in GraphResponse for /me/friends call
 *//*from w ww .j a v  a2s . c  o m*/
public static JSONArray getDataFromResponse(GraphResponse response) {
    JSONObject graphObject = response.getJSONObject();
    return graphObject.optJSONArray("data");
}

From source file:curt.android.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException, InterruptedException {

    String contents = HttpHelper.downloadViaHttp("https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn,
            HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;/*from  ww w  . j av a  2s . co m*/
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>();
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e.toString());
    }

    Collection<String> newTexts = new ArrayList<String>();

    if (title != null && title.length() > 0) {
        newTexts.add(title);
    }

    if (authors != null && !authors.isEmpty()) {
        boolean first = true;
        StringBuilder authorsText = new StringBuilder();
        for (String author : authors) {
            if (first) {
                first = false;
            } else {
                authorsText.append(", ");
            }
            authorsText.append(author);
        }
        newTexts.add(authorsText.toString());
    }

    if (pages != null && pages.length() > 0) {
        newTexts.add(pages + "pp.");
    }

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}