Example usage for org.json JSONArray optJSONObject

List of usage examples for org.json JSONArray optJSONObject

Introduction

In this page you can find the example usage for org.json JSONArray optJSONObject.

Prototype

public JSONObject optJSONObject(int index) 

Source Link

Document

Get the optional JSONObject associated with an index.

Usage

From source file:com.phelps.liteweibo.model.weibo.GeoList.java

public static GeoList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }/*from w  w  w.  j a  va2 s .  c  o  m*/

    GeoList geoList = new GeoList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);

        JSONArray jsonArray = jsonObject.optJSONArray("geos");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            geoList.Geos = new ArrayList<Geo>(length);
            for (int ix = 0; ix < length; ix++) {
                geoList.Geos.add(Geo.parse(jsonArray.optJSONObject(ix)));
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    return geoList;
}

From source file:com.alchemiasoft.common.model.Book.java

public static List<Book> allFrom(@NonNull JSONArray jsonArr) {
    final List<Book> books = new ArrayList<>();
    for (int i = 0; i < jsonArr.length(); i++) {
        final Book book = oneFrom(jsonArr.optJSONObject(i));
        books.add(book);/*from  ww  w  . j  a  v  a 2 s . co m*/
    }
    return books;
}

From source file:com.phonegap.plugins.childbrowser.ChildBrowser.java

/**
 * Executes the request and returns boolean.
 *
 * @param action          The action to execute.
 * @param args            JSONArry of arguments for the plugin.
 * @param callbackContext The callback context used when calling back into JavaScript.
 * @return                boolean//from   w  ww .  j a  v a2s . c o  m
 */
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    Log.d(LOG_TAG, action);
    String result = "";

    if (action.equals("showWebPage")) {
        Log.d(LOG_TAG, args.getString(0));
        Log.d(LOG_TAG, action);

        // If the ChildBrowser is already open then throw an error
        if (dialog != null && dialog.isShowing()) {
            callbackContext.error("ChildBrowser is already open");
        } else {
            this.callbackContext = callbackContext;
            result = this.showWebPage(args.getString(0), args.optJSONObject(1));

            if (result.length() > 0) {
                callbackContext.error(result);
            } else {
                JSONObject obj = new JSONObject();
                obj.put("type", BROWSER_OPENED);
                sendUpdate(obj, true);
            }
            Log.d(LOG_TAG, result);
        }
        return true;
    } else if (action.equals("close")) {
        closeDialog();

        JSONObject obj = new JSONObject();
        obj.put("type", CLOSE_EVENT);

        sendUpdate(obj, false);
        return true;
    } else if (action.equals("openExternal")) {
        result = this.openExternal(args.getString(0), args.optBoolean(1));
        if (result.length() > 0) {
            callbackContext.error(result);
        } else {
            JSONObject obj = new JSONObject();
            obj.put("type", OPEN_EXTERNAL_EVENT);
            sendUpdate(obj, true);
        }
        return true;
    }
    return false;
}

From source file:com.rjfun.cordova.qq.QQPlugin.java

@Override
public boolean execute(String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException {
    PluginResult result = null;// w w  w. ja v  a  2  s . co m

    if (ACTION_SET_OPTIONS.equals(action)) {
        JSONObject options = inputs.optJSONObject(0);
        this.setOptions(options);
        result = new PluginResult(Status.OK);

    } else if (ACTION_SHARE.equals(action)) {
        JSONObject options = inputs.optJSONObject(0);
        if (options.length() > 1) {
            this.setOptions(options);
        }
        boolean isOk = this.share(options);

        // we send callback in qq callback
        currentCallbackContext = callbackContext;
        return true;

    } else {
        Log.w(LOGTAG, String.format("Invalid action passed: %s", action));
        result = new PluginResult(Status.INVALID_ACTION);
    }

    if (result != null)
        sendPluginResult(result, callbackContext);

    return true;
}

From source file:org.bd2kccc.bd2kcccpubmed.Crawler.java

public static void main(String[] args) {
    HashMap<Integer, ArrayList<String>> publications = new HashMap();

    for (int i = 0; i < BD2K_CENTERS.length; i++) {
        String searchUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term="
                + BD2K_GRANTS[i] + "[Grant%20Number]&retmode=json&retmax=1000";

        System.out.println(searchUrl);
        HttpRequest request = HttpRequest.get(searchUrl);
        JSONObject req = new JSONObject(request.body());
        JSONArray idlist = req.getJSONObject("esearchresult").getJSONArray("idlist");
        System.out.println(BD2K_CENTERS[i] + ": " + idlist.length());
        for (int j = 0; j < idlist.length(); j++) {
            int pmid = idlist.optInt(j);
            if (!publications.containsKey(pmid)) {
                ArrayList<String> centerList = new ArrayList();
                centerList.add(BD2K_CENTERS[i]);
                publications.put(pmid, centerList);
            } else {
                publications.get(pmid).add(BD2K_CENTERS[i]);
            }/*from w ww . j  a  va  2s.co  m*/
        }
    }

    Integer[] pmids = publications.keySet().toArray(new Integer[0]);
    int collaborations = 0;
    for (int i = 0; i < pmids.length; i++)
        if (publications.get(pmids[i]).size() > 1)
            collaborations++;

    System.out.println(pmids.length + " publications found.");
    System.out.println(collaborations + " BD2K Center collaborations found.");
    String summaryUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&retmode=json&rettype=abstract&id="
            + pmids[0];
    for (int i = 1; i < pmids.length; i++)
        summaryUrl += "," + pmids[i];

    System.out.println(summaryUrl);
    HttpRequest request = HttpRequest.get(summaryUrl);
    JSONObject result = new JSONObject(request.body()).getJSONObject("result");

    ArrayList<Publication> publicationStructs = new ArrayList();

    for (int i = 0; i < pmids.length; i++) {
        JSONObject pub = result.getJSONObject("" + pmids[i]);
        Publication publication = new Publication();
        publication.pmid = pmids[i];
        publication.centers = publications.get(pmids[i]);
        publication.name = pub.optString("title", "NO_TITLE");
        //remove &lt;i&gt; and &lt;/i&gt;
        //replace &amp;amp; with &
        publication.name = unescapeHtml4(publication.name);
        publication.date = pub.optString("sortpubdate", "1066/01/01 00:00").substring(0, 10);
        publication.date = publication.date.replaceAll("/", "-");

        JSONArray articleIDs = pub.getJSONArray("articleids");
        for (int j = 0; j < articleIDs.length(); j++) {
            JSONObject id = articleIDs.optJSONObject(j);
            if (id.optString("idtype").equals("doi"))
                publication.doi = id.optString("value");
        }

        String issue = pub.optString("issue");
        if (!issue.isEmpty())
            issue = "(" + issue + ")";

        publication.citation = pub.optString("source") + ". " + pub.optString("pubdate") + ";"
                + pub.optString("volume") + issue + ":" + pub.optString("pages") + ".";

        publication.authors = new ArrayList();
        JSONArray aut = pub.getJSONArray("authors");
        for (int j = 0; j < aut.length(); j++) {
            publication.authors.add(aut.getJSONObject(j).optString("name"));
        }

        publicationStructs.add(publication);
    }

    Collections.sort(publicationStructs);

    for (Publication p : publicationStructs) {
        if (p.isTool())
            System.out.println(p.name);
    }

    JSONArray outputData = new JSONArray();

    for (Publication p : publicationStructs) {
        JSONArray row = new JSONArray();
        row.put(0, p.getName());
        row.put(1, p.getType());
        row.put(2, p.getDate());
        row.put(3, p.getCenter());
        row.put(4, p.getInitiative());
        row.put(5, p.getDescription());
        outputData.put(row);
    }

    System.out.println(outputData.toString(1));

}

From source file:synapticloop.b2.response.B2ListBucketsResponse.java

/**
 * Instantiate a list bucket response with the JSON response as a string from 
 * the API call.  This response is then parsed into the relevant fields.
 * //  www. j  a v  a 2s  .com
 * @param json The response (in JSON format)
 * 
 * @throws B2ApiException if there was an error parsing the response
 */
public B2ListBucketsResponse(final String json) throws B2ApiException {
    super(json);

    buckets = new ArrayList<>();
    JSONArray optJSONArray = this.readObjects(B2ResponseProperties.KEY_BUCKETS);
    for (int i = 0; i < optJSONArray.length(); i++) {
        buckets.add(new B2BucketResponse(optJSONArray.optJSONObject(i)));
    }

    this.warnOnMissedKeys();
}

From source file:com.connectsdk.cordova.ConnectSDKCordova.java

void startDiscovery(JSONArray args, final CallbackContext callbackContext) throws JSONException {
    initDiscoveryManagerWrapper();/*from   w w  w. j av a 2  s  .  c o m*/

    if (args.length() > 0) {
        JSONObject config = args.optJSONObject(0);
        discoveryManagerWrapper.configure(config);
    }

    discoveryManagerWrapper.setCallbackContext(callbackContext);
    discoveryManagerWrapper.start();
}

From source file:com.adobe.phonegap.contentsync.Sync.java

private void sync(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
    // get args/* w  w w.java  2  s .c om*/
    final String src = args.getString(0);
    final String id = args.getString(1);
    final JSONObject headers;
    if (args.optJSONObject(3) != null) {
        headers = args.optJSONObject(3);
    } else {
        headers = new JSONObject();
    }
    final boolean copyCordovaAssets;
    final boolean copyRootApp = args.getBoolean(5);
    final boolean trustEveryone = args.getBoolean(7);
    if (copyRootApp) {
        copyCordovaAssets = true;
    } else {
        copyCordovaAssets = args.getBoolean(4);
    }
    final String manifestFile = args.getString(8);
    Log.d(LOG_TAG, "sync called with id = " + id + " and src = " + src + "!");

    final ProgressEvent progress = createProgressEvent(id);

    /**
     * need to clear cache or Android won't pick up on the replaced
     * content
     */
    cordova.getActivity().runOnUiThread(new Runnable() {
        public void run() {
            webView.clearCache(true);
        }
    });

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            synchronized (progress) {
                if (progress.isAborted()) {
                    return;
                }
            }

            String outputDirectory = getOutputDirectory(id);

            // Check to see if we should just return the cached version
            String type = args.optString(2, TYPE_REPLACE);
            Log.d(LOG_TAG, "type = " + type);
            File dir = new File(outputDirectory);
            Log.d(LOG_TAG, "dir = " + dir.exists());

            if (type.equals(TYPE_LOCAL) && !dir.exists()) {
                if ("null".equals(src) && (copyRootApp || copyCordovaAssets)) {
                    if (copyRootApp) {
                        copyRootApp(outputDirectory, manifestFile);
                    }
                    if (copyCordovaAssets) {
                        copyCordovaAssets(outputDirectory);
                    }

                } else {
                    type = TYPE_REPLACE;
                }
            }

            if (!dir.exists()) {
                dir.mkdirs();
            }

            if (!type.equals(TYPE_LOCAL)) {
                // download file
                if (download(src, createDownloadFileLocation(id), headers, progress, callbackContext,
                        trustEveryone)) {
                    // update progress with zip file
                    File targetFile = progress.getTargetFile();
                    Log.d(LOG_TAG, "downloaded = " + targetFile.getAbsolutePath());

                    // Backup existing directory
                    File backup = backupExistingDirectory(outputDirectory, type, dir);

                    // @TODO: Do we do this even when type is local?
                    if (copyRootApp) {
                        copyRootApp(outputDirectory, manifestFile);
                    }

                    boolean win = false;
                    if (isZipFile(targetFile)) {
                        win = unzipSync(targetFile, outputDirectory, progress, callbackContext);
                    } else {
                        // copy file to ID
                        win = targetFile.renameTo(new File(outputDirectory));
                        progress.setLoaded(1);
                        progress.setTotal(1);
                        progress.setStatus(STATUS_EXTRACTING);
                        progress.updatePercentage();
                    }

                    // delete temp file
                    targetFile.delete();

                    if (copyCordovaAssets) {
                        copyCordovaAssets(outputDirectory);
                    }

                    if (win) {
                        // success, remove backup
                        removeFolder(backup);
                    } else {
                        // failure, revert backup
                        removeFolder(dir);
                        backup.renameTo(dir);
                    }
                } else {
                    return;
                }
            }

            // complete
            synchronized (activeRequests) {
                activeRequests.remove(id);
            }

            // Send last progress event
            progress.setStatus(STATUS_COMPLETE);
            updateProgress(callbackContext, progress);

            // Send completion message
            try {
                JSONObject result = new JSONObject();
                result.put(PROP_LOCAL_PATH, outputDirectory);
                result.put(PROP_CACHED, type.equals(TYPE_LOCAL));
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
            } catch (JSONException e) {
                // never happens
            }
        }
    });
}

From source file:com.inbeacon.cordova.CordovaInbeaconManager.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action          The action to execute.
 * @param args            JSONArray of arguments for the plugin.
 * @param callbackContext The callback id used when calling back into JavaScript.
 * @return                True if the action was valid, false if not.
 *//*from  ww  w .  ja  va  2 s .  c om*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

    if ("initialize".equals(action)) {
        initialize(args.optJSONObject(0), callbackContext);
    } else if ("attachUser".equals(action)) {
        attachUser(args.optJSONObject(0), callbackContext);
    } else if ("detachUser".equals(action)) {
        detachUser(callbackContext);
    } else if ("refresh".equals(action)) {
        refresh(callbackContext);
    } else if ("checkCapabilitiesAndRights".equals(action)) {
        verifyCapabilities(callbackContext);
    } else if ("askPermissions".equals(action)) {
        askPermissions(callbackContext);
    } else if ("startListener".equals(action)) {
        registerEventCallback(callbackContext);
    } else if ("stopListener".equals(action)) {
        unregisterEventCallback(callbackContext);
        // iOS only methods
    } else if ("setLogLevel".equals(action)) {
        callbackContext.error("setLogLevel is only available on iOS");
    } else if ("checkCapabilitiesAndRightsWithAlert".equals(action)) {
        callbackContext.error("checkCapabilitiesAndRightsWithAlert is only available on iOS");
    } else if ("getInRegions".equals(action)) {
        callbackContext.error("getInRegions is only available on iOS");
    } else if ("getBeaconState".equals(action)) {
        callbackContext.error("getBeaconState is only available on iOS");
    } else {
        return false;
    }
    return true;
}

From source file:com.facebook.login.LoginClient.java

/**
 * This parses a server response to a call to me/permissions.  It will return the list of
 * granted permissions. It will optionally update an access token with the requested permissions.
 *
 * @param response The server response//from  w w w .  j a  v  a2 s  . co  m
 * @return A list of granted permissions or null if an error
 */
private static PermissionsPair handlePermissionResponse(GraphResponse response) {
    if (response.getError() != null) {
        return null;
    }

    JSONObject result = response.getJSONObject();
    if (result == null) {
        return null;
    }

    JSONArray data = result.optJSONArray("data");
    if (data == null || data.length() == 0) {
        return null;
    }
    List<String> grantedPermissions = new ArrayList<String>(data.length());
    List<String> declinedPermissions = new ArrayList<String>(data.length());

    for (int i = 0; i < data.length(); ++i) {
        JSONObject object = data.optJSONObject(i);
        String permission = object.optString("permission");
        if (permission == null || permission.equals("installed")) {
            continue;
        }
        String status = object.optString("status");
        if (status == null) {
            continue;
        }
        if (status.equals("granted")) {
            grantedPermissions.add(permission);
        } else if (status.equals("declined")) {
            declinedPermissions.add(permission);
        }
    }

    return new PermissionsPair(grantedPermissions, declinedPermissions);
}