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:at.alladin.rmbt.android.util.ControlServerConnection.java

private JSONArray sendRequest(final URI hostUrl, final JSONObject requestData, final String fieldName) {
    // getting JSON string from URL
    //Log.d(DEBUG_TAG, "request to "+ hostUrl);       
    final JSONObject response = jParser.sendJSONToUrl(hostUrl, requestData);

    if (response != null)
        try {/*from w w  w. ja  va  2s .  c  om*/
            final JSONArray errorList = response.optJSONArray("error");

            if (errorList == null || errorList.length() == 0) {
                return getResponseField(response, fieldName);
            } else {
                hasError = true;
                for (int i = 0; i < errorList.length(); i++) {

                    if (i > 0)
                        errorMsg += "\n";
                    errorMsg += errorList.getString(i);
                }

                System.out.println(errorMsg);

                //return getResponseField(response, fieldName);
            }

            // }
        } catch (final JSONException e) {
            hasError = true;
            errorMsg = "Error parsing server response";
            e.printStackTrace();
        }
    else {
        hasError = true;
        errorMsg = "No response";
    }

    return null;

}

From source file:at.alladin.rmbt.controlServer.filter.ResultStatusFilter.java

@Override
protected void afterHandle(Request request, Response response) {
    System.out.println("STATUS FILTER");
    try {//from  w  ww  .  j  a  v a  2 s  .  co  m
        final JSONObject json = new JSONObject(response.getEntityAsText());
        final JSONArray errorArray = json.optJSONArray("error");
        if (errorArray != null && errorArray.length() > 0) {
            response.setStatus(Status.SERVER_ERROR_INTERNAL);
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        response.setStatus(Status.SERVER_ERROR_INTERNAL);
    }
    super.afterHandle(request, response);
}

From source file:com.ammobyte.radioreddit.api.GetSongInfo.java

@Override
protected Boolean doInBackground(String... params) {
    final String cookie = params[0]; // This will be null if not logged in

    // Prepare GET with cookie, execute it, parse response as JSON
    JSONObject response = null;/* w w w.ja v a  2  s .  c  o m*/
    try {
        final HttpClient httpClient = new DefaultHttpClient();
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("url", mSong.reddit_url));
        final HttpGet httpGet = new HttpGet(
                "http://www.reddit.com/api/info.json?" + URLEncodedUtils.format(nameValuePairs, "utf-8"));
        if (cookie != null) {
            // Using HttpContext, CookieStore, and friends didn't work
            httpGet.setHeader("Cookie", "reddit_session=" + cookie);
        }
        httpGet.setHeader("User-Agent", RedditApi.USER_AGENT);
        final HttpResponse httpResponse = httpClient.execute(httpGet);
        response = new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
    } catch (UnsupportedEncodingException e) {
        Log.i(RedditApi.TAG, "UnsupportedEncodingException while getting song info", e);
    } catch (ClientProtocolException e) {
        Log.i(RedditApi.TAG, "ClientProtocolException while getting song info", e);
    } catch (IOException e) {
        Log.i(RedditApi.TAG, "IOException while getting song info", e);
    } catch (ParseException e) {
        Log.i(RedditApi.TAG, "ParseException while getting song info", e);
    } catch (JSONException e) {
        Log.i(RedditApi.TAG, "JSONException while getting song info", e);
    }

    // Check for failure
    if (response == null) {
        Log.i(RedditApi.TAG, "Response is null");
        return false;
    }

    // Get the info we want
    final JSONObject data1 = response.optJSONObject("data");
    if (data1 == null) {
        Log.i(RedditApi.TAG, "First data is null");
        return false;
    }
    final String modhash = data1.optString("modhash", "");
    if (modhash.length() > 0) {
        mService.setModhash(modhash);
    }
    final JSONArray children = data1.optJSONArray("children");
    if (children == null) {
        Log.i(RedditApi.TAG, "Children is null");
        return false;
    }
    final JSONObject child = children.optJSONObject(0);
    if (child == null) {
        // This is common if the song hasn't been submitted to reddit yet
        // so we intentionally don't log this case
        return false;
    }
    final String kind = child.optString("kind");
    if (kind == null) {
        Log.i(RedditApi.TAG, "Kind is null");
        return false;
    }
    final JSONObject data2 = child.optJSONObject("data");
    if (data2 == null) {
        Log.i(RedditApi.TAG, "Second data is null");
        return false;
    }
    final String id = data2.optString("id");
    if (id == null) {
        Log.i(RedditApi.TAG, "Id is null");
        return false;
    }
    final int score = data2.optInt("score");
    Boolean likes = null;
    if (!data2.isNull("likes")) {
        likes = data2.optBoolean("likes");
    }
    final boolean saved = data2.optBoolean("saved");

    // Modify song with collected info
    if (kind != null && id != null) {
        mSong.reddit_id = kind + "_" + id;
    } else {
        mSong.reddit_id = null;
    }
    mSong.upvoted = (likes != null && likes == true);
    mSong.downvoted = (likes != null && likes == false);
    mSong.votes = score;
    mSong.saved = saved;

    return true;
}

From source file:com.facebook.internal.Utility.java

private static Map<String, Map<String, DialogFeatureConfig>> parseDialogConfigurations(
        JSONObject dialogConfigResponse) {
    HashMap<String, Map<String, DialogFeatureConfig>> dialogConfigMap = new HashMap<String, Map<String, DialogFeatureConfig>>();

    if (dialogConfigResponse != null) {
        JSONArray dialogConfigData = dialogConfigResponse.optJSONArray("data");
        if (dialogConfigData != null) {
            for (int i = 0; i < dialogConfigData.length(); i++) {
                DialogFeatureConfig dialogConfig = DialogFeatureConfig
                        .parseDialogConfig(dialogConfigData.optJSONObject(i));
                if (dialogConfig == null) {
                    continue;
                }/*  ww  w . jav a2  s .com*/

                String dialogName = dialogConfig.getDialogName();
                Map<String, DialogFeatureConfig> featureMap = dialogConfigMap.get(dialogName);
                if (featureMap == null) {
                    featureMap = new HashMap<String, DialogFeatureConfig>();
                    dialogConfigMap.put(dialogName, featureMap);
                }
                featureMap.put(dialogConfig.getFeatureName(), dialogConfig);
            }
        }
    }

    return dialogConfigMap;
}

From source file:edu.txstate.dmlab.clusteringwiki.rest.ClusterController.java

/**
 * Recursively sort cluster labels in each level
 * @param cluster/*from   www  . ja  v a 2s  .  com*/
 * @return
 * @throws JSONException 
 */
protected JSONObject sortChildren(final JSONObject cluster, final Map<String, List<Integer>> clusterPages)
        throws JSONException {
    JSONArray children = cluster.optJSONArray("children");
    if (children == null)
        return cluster;
    final int numChildren = children.length();
    if (numChildren < 2)
        return cluster;
    final MinDocIndexJSONClusterQueue sortQueue = new MinDocIndexJSONClusterQueue(numChildren, clusterPages);
    for (int i = 0; i < numChildren; i++) {
        JSONObject child = sortChildren(children.getJSONObject(i), clusterPages);
        sortQueue.add(child);
    }
    for (int i = 0; i < numChildren; i++)
        children.put(i, sortQueue.pop());
    cluster.put("children", children);
    return cluster;
}

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

@Override
protected void refresh() {
    // ???/*from ww  w.j a  v  a2  s  .  c  om*/
    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.mentions(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.MENTION, 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, MentionTimelineFragment.this);
                                }
                            }, errorListener)).setTag(TAG);
                }
            });
        }
    })).start();
}

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

private void loadFromCloud(long max_id) {
    mSwipeRefreshLayout.setRefreshing(true);
    CatnutAPI api = TweetAPI.mentions(0, max_id, getFetchSize(), 0, 0, 0, 0);
    mRequestQueue.add(new CatnutRequest(getActivity(), api,
            new StatusProcessor.TimelineProcessor(Status.MENTION, true), new Response.Listener<JSONObject>() {
                @Override/*from w w w .  j av a  2s  .  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, MentionTimelineFragment.this);
                }
            }, errorListener)).setTag(TAG);
}

From source file:com.norman0406.slimgress.API.Interface.Handshake.java

public Handshake(JSONObject json) throws JSONException {
    JSONObject result = json.getJSONObject("result");

    String pregameStatus = result.getJSONObject("pregameStatus").getString("action");
    if (pregameStatus.equals("CLIENT_MUST_UPGRADE"))
        mPregameStatus = PregameStatus.ClientMustUpgrade;
    else if (pregameStatus.equals("NO_ACTIONS_REQUIRED"))
        mPregameStatus = PregameStatus.NoActionsRequired;
    else/*from w  w  w.ja va  2 s  . c  o m*/
        throw new RuntimeException("unknown pregame status " + pregameStatus);

    mServerVersion = result.getString("serverVersion");

    // get player entity
    mNickname = result.optString("nickname");
    JSONArray playerEntity = result.optJSONArray("playerEntity");
    if (playerEntity != null)
        mAgent = new Agent(playerEntity, mNickname);

    mXSRFToken = result.optString("xsrfToken");

    // get knobs
    JSONObject knobs = result.optJSONObject("initialKnobs");
    if (knobs != null)
        mKnobs = new KnobsBundle(knobs);
}

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

/**
 * Fills a Message instance from JSONObject.
 *//* w  w  w.  j a  va2s  .c  om*/
public VKApiMessage parse(JSONObject source) throws JSONException {
    id = source.optInt("id");
    user_id = source.optInt("user_id");
    date = source.optLong("date");
    read_state = ParseUtils.parseBoolean(source, "read_state");
    out = ParseUtils.parseBoolean(source, "out");
    title = source.optString("title");
    body = source.optString("body");
    attachments.fill(source.optJSONArray("attachments"));
    fwd_messages = new VKList<VKApiMessage>(source.optJSONArray("fwd_messages"), VKApiMessage.class);
    emoji = ParseUtils.parseBoolean(source, "emoji");
    deleted = ParseUtils.parseBoolean(source, "deleted");
    return this;
}

From source file:com.namelessdev.mpdroid.cover.SpotifyCover.java

private static List<String> extractAlbumIds(final String response) {
    final JSONObject jsonRoot;
    final JSONArray jsonAlbums;
    JSONObject jsonAlbum;//  ww w  .j a  v a2s  .c o m
    String albumId;
    final List<String> albumIds = new ArrayList<>();

    try {
        jsonRoot = new JSONObject(response);
        jsonAlbums = jsonRoot.optJSONArray("albums");
        if (jsonAlbums != null) {
            for (int a = 0; a < jsonAlbums.length(); a++) {
                jsonAlbum = jsonAlbums.optJSONObject(a);
                if (jsonAlbum != null) {
                    albumId = jsonAlbum.optString("href");
                    if (albumId != null && !albumId.isEmpty()) {
                        albumId = albumId.replace("spotify:album:", "");
                        albumIds.add(albumId);
                    }
                }
            }
        }
    } catch (final Exception e) {
        if (CoverManager.DEBUG) {
            Log.e(TAG, "Failed to get cover URL from Spotify.", e);
        }
    }

    return albumIds;
}