Example usage for org.json JSONObject getJSONObject

List of usage examples for org.json JSONObject getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(String key) throws JSONException 

Source Link

Document

Get the JSONObject value associated with a key.

Usage

From source file:edu.stanford.junction.api.activity.ActivityScript.java

public JSONObject getRolePlatform(String role, String platform) {
    try {//from  www .j a v a  2  s .  co m
        JSONObject spec = getRoleSpec(role);
        if (spec == null)
            return null;
        spec = spec.optJSONObject("platforms");

        if (spec == null)
            return null;
        if (spec.has(platform)) {
            return spec.getJSONObject(platform);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:edu.stanford.junction.api.activity.ActivityScript.java

public void addRolePlatform(String role, String platform, JSONObject platformSpec) {
    try {//from   w  w  w  .ja v  a  2s  . c om
        if (roleSpecs == null)
            roleSpecs = new JSONObject();
        if (!roleSpecs.has(role)) {
            roleSpecs.put(role, new JSONObject());
        }

        JSONObject jsonRole = roleSpecs.getJSONObject(role);
        if (!jsonRole.has("platforms")) {
            jsonRole.put("platforms", new JSONObject());
        }

        JSONObject jsonPlatforms = jsonRole.getJSONObject("platforms");
        jsonPlatforms.put(platform, platformSpec);

        mJSON = null; // reset
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.kupriyanov.android.apps.translate.service.WorkerThread.java

/**
 * Read and return the content for a specific Wiktionary page. This makes a
 * lightweight API call, and trims out just the page content returned.
 * Because this call blocks until results are available, it should not be run
 * from a UI thread./*from   www.  j av a 2s  . co m*/
 * 
 * @param title
 *           The exact title of the Wiktionary page requested.
 * @param expandTemplates
 *           If true, expand any wiki templates found.
 * @return Exact content of page.
 * @throws ApiException
 *            If any connection or server error occurs.
 * @throws ParseException
 *            If there are problems parsing the response.
 */
public static String getPageContent(String apiQuery, boolean expandTemplates)
        throws ApiException, ParseException {

    String content = getUrlContent(apiQuery);

    Log.d(TAG, "[RESPONSE->]:" + content);

    try {
        // Drill into the JSON response to find the content body
        JSONObject response = new JSONObject(content);
        JSONObject data = response.getJSONObject("responseData");
        // JSONObject pages = data.getJSONObject("translations");
        // JSONObject page = pages.getJSONObject((String) pages.keys().next());

        // JSONArray translations = data.getJSONArray("translations");
        // JSONObject revision = translations.getJSONObject(0);

        return data.getString("translatedText");
    } catch (JSONException e) {
        throw new ParseException("Problem parsing API response:" + content, e);
    }

}

From source file:com.kupriyanov.android.apps.translate.service.WorkerThread.java

/**
 * Read and return the content for a specific Wiktionary page. This makes a
 * lightweight API call, and trims out just the page content returned.
 * Because this call blocks until results are available, it should not be run
 * from a UI thread.//from   w w w.j  ava 2 s  .  c  o  m
 * 
 * @param title
 *           The exact title of the Wiktionary page requested.
 * @param expandTemplates
 *           If true, expand any wiki templates found.
 * @return Exact content of page.
 * @throws ApiException
 *            If any connection or server error occurs.
 * @throws ParseException
 *            If there are problems parsing the response.
 */
public static String getPageContent2(String apiQuery, boolean expandTemplates)
        throws ApiException, ParseException {

    String content = getUrlContent(apiQuery);

    Log.d(TAG, "[RESPONSE->]:" + content);

    try {
        // Drill into the JSON response to find the content body
        JSONObject response = new JSONObject(content);
        JSONObject data = response.getJSONObject("data");
        // JSONObject pages = data.getJSONObject("translations");
        // JSONObject page = pages.getJSONObject((String) pages.keys().next());

        JSONArray translations = data.getJSONArray("translations");
        JSONObject revision = translations.getJSONObject(0);
        return revision.getString("translatedText");
    } catch (JSONException e) {
        throw new ParseException("Problem parsing API response:" + content, e);
    }

}

From source file:com.kupriyanov.android.apps.translate.service.WorkerThread.java

public static String detectLanguage(String apiQuery) throws ApiException, ParseException {

    String content = getUrlContent(apiQuery);

    Log.d(TAG, "[RESPONSE->]:" + content);

    try {// w  w w  .j  av a 2  s  .  c o m
        // Drill into the JSON response to find the content body
        final JSONObject response = new JSONObject(content);
        final JSONObject data = response.getJSONObject("data");
        final JSONArray detections = data.getJSONArray("detections");
        final JSONArray detectionArr = detections.getJSONArray(0);
        final JSONObject detectionObj = detectionArr.getJSONObject(0);

        //       language": "de",
        //        "isReliable": false,
        //        "confidence": 1.0

        return detectionObj.getString("language");
    } catch (JSONException e) {
        throw new ParseException("Problem parsing API response:" + content, e);
    }

}

From source file:com.abeo.tia.noordin.ProcessCaseLoanPrincipal.java

private void setallvalues(String arg2) {

    JSONArray jObj = null;//from  w w w  . j  a  va2s .co  m
    try {
        jObj = new JSONArray(arg2.toString());

        for (int i = 0; i < jObj.length(); i++) {
            JSONObject jsonobject = jObj.getJSONObject(i);
            file_open_date.setText(jsonobject.getString("FileOpenDate"));
            case_file_no.setText(jsonobject.getString("CaseFileNo"));
            case_type.setText(jsonobject.getString("CaseType"));
            Scase_status = jsonobject.getString("CaseStatus");

            JSONObject obj1 = jsonobject.getJSONObject("LoanPrinciple");

            req_for_redemption.getText().toString();

            req_for_redemption.setText(obj1.getString("ReqRedStatement"));
            red_state_date.setText(obj1.getString("RedStmtDate"));
            red_payment_date.setText(obj1.getString("RedPayDate"));
            loan_case_no.setText(obj1.getString("LoanCaseNo"));
            project.setText(obj1.getString("Project"));
            master_bankname = obj1.getString("MasterBankName");
            branch_name.setText(obj1.getString("BranchName"));
            addr.setText(obj1.getString("Address"));
            pa_name.setText(obj1.getString("PAName"));
            bank_ref.setText(obj1.getString("BankRef"));
            bank_instr_date.setText(obj1.getString("BankInsDate"));
            letter_offer_date.setText(obj1.getString("LOFDate"));
            bank_solicitor.setText(obj1.getString("BankSolicitor"));
            solicitor_loc.setText(obj1.getString("SoliLoc"));
            solicitor_ref.setText(obj1.getString("SoliRef"));
            type_facility.setText(obj1.getString("TypeofFacility"));
            facility_amt.setText(obj1.getString("FacilityAmt"));
            repayment.setText(obj1.getString("Repaymt"));
            interest_rate.setText(obj1.getString("IntrstRate"));
            monthly_installment.setText(obj1.optString("MonthlyInstmt"));
            term_loanamt.setText(obj1.getString("TermLoanAmt"));
            interest.setText(obj1.optString("Interest"));
            od_loan.setText(obj1.getString("ODLoan"));
            mrta.setText(obj1.getString("MRTA"));
            bank_guarantee.setText(obj1.optString("BankGuarantee"));
            letter_credit.setText(obj1.getString("LetterofCredit"));
            trust_receipt.setText(obj1.optString("TrustReceipt"));
            others.setText(obj1.getString("Others"));

            LoanDet1.setText(obj1.getString("LoanDet1"));
            LoanDet2.setText(obj1.getString("LoanDet2"));
            LoanDet3.setText(obj1.getString("LoanDet3"));
            LoanDet4.setText(obj1.getString("LoanDet4"));
            LoanDet5.setText(obj1.getString("LoanDet5"));

            Skiv = jsonobject.getString("KIV");
            SLoanTypeOfLoans = obj1.getString("TypeofLoan");

            if (obj1.getString("RepByFirm").toString().equals("Y")) {
                rep_firm.setChecked(true);
            } else {
                rep_firm.setChecked(false);
            }
        }
        System.out.println(jObj);

        dropdownstatus();
        dropdownKIV();
        dropdownLTY();
        dropdownBankDeveloperSolicitor();
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

From source file:es.ucm.look.data.remote.restful.RestMethod.java

/**
 * To know the 'number' of last id inserted in the Server
 * /*  www . j  a  v a2 s  .com*/
 * @return
 */
public static int getLastId() {

    int result = -1;

    String query = URLEncoder.encode("SELECT e FROM Main e ORDER BY e.id DESC");

    String params = "?max=1&query=" + query;

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet(ConfigNet.getInstance().getURL("mains/" + params));

    // Accept Text/plain
    httpget.addHeader("accept", "application/json");

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);

        // Get the response entity
        HttpEntity entity = response.getEntity();

        // If response entity is not null
        if (entity != null) {

            // get entity contents and convert it to string
            InputStream instream = entity.getContent();
            String resultResponse = convertStreamToString(instream);

            // construct a JSON object with result
            try {
                // extract field id of the json
                JSONObject json = new JSONObject(resultResponse);
                JSONObject mainEntity = json.getJSONObject("main");
                result = mainEntity.getInt("id");

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // Closing the input stream will trigger connection release
            instream.close();
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Return the result
    return result;
}

From source file:com.domuslink.api.DomusHandler.java

public String[] getDomusApiVersion() throws Exception {
    JSONObject theApi = null;//from  w w  w .  j  a v  a2  s.  c  om
    JSONObject theResponse = null;
    String[] theVersionInfo;

    if (this.hostPath != null || this.hostPath.length() != 0) {
        ApiHandler.prepareUserAgent(this.c, authPass, hostPath);
        try {
            theResponse = ApiHandler.getPageContent(this, "version", null);
        } catch (Exception e) {
            Log.e(TAG, "Error getting version page content at " + this.hostPath, e);
            throw e;
        }

        try {
            theApi = theResponse.getJSONObject("api");
        } catch (Exception e) {
            Log.e(TAG, "Error getting version from JSONObject", e);
            throw e;
        }
        theVersionInfo = new String[2];
        try {
            theVersionInfo[0] = theApi.getString("name");
            theVersionInfo[1] = theApi.getString("version");
        } catch (Exception e) {
            Log.e(TAG, "Error getting version info from JSONArray", e);
            throw e;
        }
    } else
        theVersionInfo = EMPTY_LIST;

    return theVersionInfo;
}

From source file:com.ProfessorPopTart.alternateouyastore.MainActivity.java

/**
 * This will get the img url of a game from the JSON response
 *
 * @param urlResults  String JSON response form the download url request
 * @returns the link to download the apk
 *//*w w  w. jav a 2 s  .  c o m*/
private String getLink(String urlResults) {
    try {
        JSONObject MyResults = new JSONObject(urlResults);
        String url = MyResults.getJSONObject("app").getString("downloadLink");
        return url;
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
}

From source file:com.fvd.nimbus.BrowseActivity.java

@Override
public void onTaskComplete(String result, String action) {
    /*if (progressDialog != null)
    progressDialog.dismiss();*//*  w  ww  . j  av a 2s. c  o  m*/
    try {
        JSONObject root = new JSONObject(result);
        int error = root.getInt("errorCode");
        if (error == 0) {
            if (action.equalsIgnoreCase("user:auth")) {
                sessionId = root.getJSONObject("body").getString("sessionid");
                Editor e = prefs.edit();
                e.putString("userMail", userMail);
                e.putString("userPass", userPass);
                e.putString("sessionId", sessionId);
                e.commit();

                appSettings.sessionId = sessionId;
                appSettings.userMail = userMail;
                appSettings.userPass = userPass;
                if (lastAction != "") {
                    serverHelper.getInstance().sendRequest(lastAction, "", "");
                } else if (clipData != null && clipData.getContent().length() > 0) {
                    /*sendNote(wv.getTitle(), clipData.getContent(),parent,tag);
                    clipData.setContent("");*/
                    if (prefs.getBoolean("check_fast", false)) {
                        sendNote(clipData.getTitle(), clipData.getContent(), parent, tag);
                        clipData.setContent("");
                    } else {
                        serverHelper.getInstance().setCallback(this, this);
                        if (appSettings.sessionId.length() > 0) {
                            serverHelper.getInstance().sendRequest("notes:getFolders", "", "");
                        }
                    }
                }
                /*else if(selBuff.length()>0){
                           
                if(prefs.getBoolean("check_fast", false)){
                   sendNote(wv.getTitle(), selBuff, parent, tag);
                    selBuff="";
                }
                else {
                serverHelper.getInstance().setCallback(this,this);
                if(appSettings.sessionId.length()>0) {
                   serverHelper.getInstance().sendRequest("notes:getFolders", "","");
                   }
                }
                  }*/

            } else if (action.equalsIgnoreCase("notes:getfolders")) {

                //ArrayList<FolderItem>items=new ArrayList<FolderItem>();
                //ArrayList<FolderListItem>items=new ArrayList<FolderListItem>();
                try {
                    result = URLDecoder.decode(result, "UTF-16");
                    clipData.setData(result);
                    String cr = prefs.getString("remFolderId", "default");
                    if (cr == null || cr == "")
                        cr = "default";
                    clipData.setId(cr);
                    clipData.setTitle(wv.getTitle());
                    clipData.setTags("androidclipper");
                    Intent intent = new Intent(getApplicationContext(), tagsActivity.class);
                    intent.putExtra("xdata", clipData);
                    /*intent.putExtra("current", cr);
                    intent.putExtra("title", wv.getTitle());
                    intent.putExtra("tags", "androidclipper");*/

                    startActivityForResult(intent, 7);
                    //overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
                    overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out);
                    clipData.setData("");
                } catch (Exception Ex) {
                    appSettings.appendLog("prefs:onTaskComplete " + Ex.getMessage());
                }
            } else if (action.equalsIgnoreCase("user:authstate")) {
                boolean auth = root.getJSONObject("body").getBoolean("authorized");
                Toast.makeText(getApplicationContext(), "User " + (auth ? "authorized" : "not authorized"),
                        Toast.LENGTH_LONG).show();
            } else if ("notes:update".equalsIgnoreCase(action)) {
                showArticleSuccess();
            } else if ("notes:share".equalsIgnoreCase(action)) {
                String url = root.getString("url");
                showArticleDlg(url);
                //Toast.makeText(getApplicationContext(), "The fragment was successfully saved to your Nimbus account", Toast.LENGTH_LONG).show();
            } else if ("user_register".equals(action)) {
                sendRequest("user:auth",
                        String.format("\"email\":\"%s\",\"password\":\"%s\"", userMail, userPass));
            }
        } else {
            if (action.equalsIgnoreCase("user:auth")) {
                lastAction = "";
                showSettings();
            } else if (error == -6) {
                if (action == "notes:getFolders")
                    lastAction = action;
                else
                    lastAction = "";
                showSettings();
            } else
                Toast.makeText(getApplicationContext(),
                        String.format("Error: %s", serverHelper.errorMsg(error)), Toast.LENGTH_LONG).show();
        }
    } catch (Exception Ex) {
    }
}