Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

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

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

From source file:org.wso2.appmanager.integration.test.cases.PublisherCreateWebAppTestCase.java

@Test(description = TEST_DESCRIPTION)
public void testPublisherCreateWebApp() throws Exception {
    HttpResponse appCreateResponse = appmPublisherRestClient.webAppCreate(appName, context, appVersion,
            trackingCode, appCreatorUserName);
    int appCreateResponseCode = appCreateResponse.getResponseCode();
    assertTrue(appCreateResponseCode == 200, appCreateResponseCode + " status code received.");
    JSONObject appCreateResponseData = new JSONObject(appCreateResponse.getData());
    assertEquals(appCreateResponseData.getString(AppmTestConstants.MESSAGE), "asset added",
            "Asset has not added successfully");
    assertNotNull(appCreateResponseData.getString(AppmTestConstants.ID), "app id is null");
}

From source file:org.onepf.oms.data.SkuDetails.java

public SkuDetails(String json) throws JSONException {
    JSONObject o = new JSONObject(json);
    _sku = o.getString("productId");
    _type = o.optString("type");
    _price = o.optString("price");
    _title = o.optString("title");
    _description = o.optString("description");
}

From source file:de.schildbach.wallet.data.ExchangeRatesProvider.java

private Map<String, ExchangeRate> requestExchangeRates() {
    final Stopwatch watch = Stopwatch.createStarted();

    final Request.Builder request = new Request.Builder();
    request.url(BITCOINAVERAGE_URL);
    request.header("User-Agent", userAgent);

    final Call call = Constants.HTTP_CLIENT.newCall(request.build());
    try {//  ww  w . ja  v  a2 s  .com
        final Response response = call.execute();
        if (response.isSuccessful()) {
            final String content = response.body().string();
            final JSONObject head = new JSONObject(content);
            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (currencyCode.startsWith("BTC")) {
                    final String fiatCurrencyCode = currencyCode.substring(3);
                    if (!fiatCurrencyCode.equals(MonetaryFormat.CODE_BTC)
                            && !fiatCurrencyCode.equals(MonetaryFormat.CODE_MBTC)
                            && !fiatCurrencyCode.equals(MonetaryFormat.CODE_UBTC)) {
                        final JSONObject exchangeRate = head.getJSONObject(currencyCode);
                        final JSONObject averages = exchangeRate.getJSONObject("averages");
                        try {
                            final Fiat rate = parseFiatInexact(fiatCurrencyCode, averages.getString("day"));
                            if (rate.signum() > 0)
                                rates.put(fiatCurrencyCode, new ExchangeRate(
                                        new org.bitcoinj.utils.ExchangeRate(rate), BITCOINAVERAGE_SOURCE));
                        } catch (final IllegalArgumentException x) {
                            log.warn("problem fetching {} exchange rate from {}: {}", currencyCode,
                                    BITCOINAVERAGE_URL, x.getMessage());
                        }
                    }
                }
            }

            watch.stop();
            log.info("fetched exchange rates from {}, {} chars, took {}", BITCOINAVERAGE_URL, content.length(),
                    watch);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", response.code(),
                    BITCOINAVERAGE_URL);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + BITCOINAVERAGE_URL, x);
    }

    return null;
}

From source file:com.ledger.android.u2f.bridge.MainActivity.java

private U2FContext parseU2FContext(String data) {
    try {//ww  w  . j a  va 2  s  . co m
        JSONObject json = new JSONObject(data);
        String requestType = json.getString(TAG_JSON_TYPE);
        if (requestType.equals(SIGN_REQUEST_TYPE)) {
            return parseU2FContextSign(json);
        } else if (requestType.equals(REGISTER_REQUEST_TYPE)) {
            return parseU2FContextRegister(json);
        } else {
            Log.e(TAG, "Invalid request type");
            return null;
        }
    } catch (JSONException e) {
        Log.e(TAG, "Error decoding request");
        return null;
    }

}

From source file:com.ledger.android.u2f.bridge.MainActivity.java

private U2FContext parseU2FContextSign(JSONObject json) {
    try {// www.ja  va  2s . c  om
        String appId = json.getString(TAG_JSON_APPID);
        byte[] challenge = Base64.decode(json.getString(TAG_JSON_CHALLENGE), Base64.URL_SAFE);
        int requestId = json.getInt(TAG_JSON_REQUESTID);
        JSONArray array = json.getJSONArray(TAG_JSON_REGISTERED_KEYS);
        Vector<byte[]> keyHandles = new Vector<byte[]>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject keyHandleItem = array.getJSONObject(i);
            if (!keyHandleItem.getString(TAG_JSON_VERSION).equals(VERSION_U2F_V2)) {
                Log.e(TAG, "Invalid handle version");
                return null;
            }
            byte[] keyHandle = Base64.decode(keyHandleItem.getString(TAG_JSON_KEYHANDLE), Base64.URL_SAFE);
            keyHandles.add(keyHandle);
        }
        return new U2FContext(appId, challenge, keyHandles, requestId, true);
    } catch (JSONException e) {
        Log.e(TAG, "Error decoding request");
        return null;
    }
}

From source file:com.ledger.android.u2f.bridge.MainActivity.java

private U2FContext parseU2FContextRegister(JSONObject json) {
    try {/*from  w w w.  j a v a  2  s  . c om*/
        byte[] challenge = null;
        String appId = json.getString(TAG_JSON_APPID);
        int requestId = json.getInt(TAG_JSON_REQUESTID);
        JSONArray array = json.getJSONArray(TAG_JSON_REGISTER_REQUESTS);
        for (int i = 0; i < array.length(); i++) {
            // TODO : only handle USB transport if several are present
            JSONObject registerItem = array.getJSONObject(i);
            if (!registerItem.getString(TAG_JSON_VERSION).equals(VERSION_U2F_V2)) {
                Log.e(TAG, "Invalid register version");
                return null;
            }
            challenge = Base64.decode(registerItem.getString(TAG_JSON_CHALLENGE), Base64.URL_SAFE);
        }
        return new U2FContext(appId, challenge, null, requestId, false);
    } catch (JSONException e) {
        Log.e(TAG, "Error decoding request");
        return null;
    }
}

From source file:com.jellymold.boss.ImageSearch.java

protected void parseResults(JSONObject jobj) throws JSONException {

    if (jobj != null) {

        setResponseCode(jobj.getInt("responsecode"));
        if (jobj.has("nextpage"))
            setNextPage(jobj.getString("nextpage"));
        if (jobj.has("prevpage"))
            setPrevPage(jobj.getString("prevpage"));
        setTotalResults(jobj.getLong("totalhits"));
        long count = jobj.getLong("count");
        setPagerCount(count);/*  ww w  . j  a va2s .c  om*/
        setPagerStart(jobj.getLong("start"));
        this.setResults(new ArrayList<ImageSearchResult>((int) count));

        if (jobj.has("resultset_images")) {

            JSONArray res = jobj.getJSONArray("resultset_images");
            for (int i = 0; i < res.length(); i++) {
                JSONObject thisResult = res.getJSONObject(i);
                ImageSearchResult imageSearchResult = new ImageSearchResult();
                imageSearchResult.setDescription(thisResult.getString("abstract"));
                imageSearchResult.setClickUrl(thisResult.getString("clickurl"));
                imageSearchResult.setDate(thisResult.getString("date"));
                imageSearchResult.setTitle(thisResult.getString("title"));
                imageSearchResult.setUrl(thisResult.getString("url"));
                imageSearchResult.setSize(thisResult.getLong("size"));
                imageSearchResult.setFilename(thisResult.getString("filename"));
                imageSearchResult.setFormat(thisResult.getString("format"));
                imageSearchResult.setHeight(thisResult.getLong("height"));
                imageSearchResult.setMimeType(thisResult.getString("mimetype"));
                imageSearchResult.setRefererClickUrl(thisResult.getString("refererclickurl"));
                imageSearchResult.setRefererUrl(thisResult.getString("refererurl"));
                imageSearchResult.setThumbnailHeight(thisResult.getLong("thumbnail_height"));
                imageSearchResult.setThumbnailWidth(thisResult.getLong("thumbnail_width"));
                imageSearchResult.setThumbnailUrl(thisResult.getString("thumbnail_url"));
                this.getResults().add(imageSearchResult);
            }
        }
    }

}

From source file:com.example.bookstoremb.utils.Utils.java

/**
 * create book from json//  w  w  w .  j a  v a  2 s .  c om
 * 
 * @param json
 * @return
 * @throws JSONException
 */
public static Book createBookFromJSON(JSONObject json) throws JSONException {
    Book book = new Book();
    book.setBookId(json.getString("bookId"));
    book.setName(json.getString("name"));
    book.setCategory(Utils.bookCategoryStringToEnum(json.getString("category")));
    book.setContent(json.getString("content"));
    return book;
}

From source file:com.example.bookstoremb.utils.Utils.java

/**
 * create author from json//  ww  w  .j av  a2  s.c o m
 * 
 * @param json
 * @return
 * @throws JSONException
 */
public static Author createAuthorFromJSON(JSONObject json) throws JSONException {
    Author author = new Author();
    author.setAuthorId(json.getString("authorId"));
    author.setName(json.getString("name"));
    author.setAddress(json.getString("address"));
    author.setPhone(json.getString("phone"));
    return author;
}

From source file:test.Testing.java

public static void main(String[] args) throws Exception {
    ////////////////////////////////////////////////////////////////////////////////////////////
    // Setup//from www.j av  a2s  .  co  m
    ////////////////////////////////////////////////////////////////////////////////////////////
    String key = "CHANGEME: YOUR_API_KEY";
    String secret = "CHANGEME: YOUR_API_SECRET";
    String version = "preview1";
    String practiceid = "000000";

    APIConnection api = new APIConnection(version, key, secret, practiceid);
    api.authenticate();

    // If you want to set the practice ID after construction, this is how.
    // api.setPracticeID("000000");

    ////////////////////////////////////////////////////////////////////////////////////////////
    // GET without parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    JSONArray customfields = (JSONArray) api.GET("/customfields");
    System.out.println("Custom fields:");
    for (int i = 0; i < customfields.length(); i++) {
        System.out.println("\t" + customfields.getJSONObject(i).get("name"));
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
    // GET with parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
    Calendar today = Calendar.getInstance();
    Calendar nextyear = Calendar.getInstance();
    nextyear.roll(Calendar.YEAR, 1);

    Map<String, String> search = new HashMap<String, String>();
    search.put("departmentid", "82");
    search.put("startdate", format.format(today.getTime()));
    search.put("enddate", format.format(nextyear.getTime()));
    search.put("appointmenttypeid", "2");
    search.put("limit", "1");

    JSONObject open_appts = (JSONObject) api.GET("/appointments/open", search);
    System.out.println(open_appts.toString());
    JSONObject appt = open_appts.getJSONArray("appointments").getJSONObject(0);
    System.out.println("Open appointment:");
    System.out.println(appt.toString());

    // add keys to make appt usable for scheduling
    appt.put("appointmenttime", appt.get("starttime"));
    appt.put("appointmentdate", appt.get("date"));

    ////////////////////////////////////////////////////////////////////////////////////////////
    // POST with parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    Map<String, String> patient_info = new HashMap<String, String>();
    patient_info.put("lastname", "Foo");
    patient_info.put("firstname", "Jason");
    patient_info.put("address1", "123 Any Street");
    patient_info.put("city", "Cambridge");
    patient_info.put("countrycode3166", "US");
    patient_info.put("departmentid", "1");
    patient_info.put("dob", "6/18/1987");
    patient_info.put("language6392code", "declined");
    patient_info.put("maritalstatus", "S");
    patient_info.put("race", "declined");
    patient_info.put("sex", "M");
    patient_info.put("ssn", "*****1234");
    patient_info.put("zip", "02139");

    JSONArray new_patient = (JSONArray) api.POST("/patients", patient_info);
    String new_patient_id = new_patient.getJSONObject(0).getString("patientid");
    System.out.println("New patient id:");
    System.out.println(new_patient_id);

    ////////////////////////////////////////////////////////////////////////////////////////////
    // PUT with parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    Map<String, String> appointment_info = new HashMap<String, String>();
    appointment_info.put("appointmenttypeid", "82");
    appointment_info.put("departmentid", "1");
    appointment_info.put("patientid", new_patient_id);

    JSONArray booked = (JSONArray) api.PUT("/appointments/" + appt.getString("appointmentid"),
            appointment_info);
    System.out.println("Booked:");
    System.out.println(booked.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // POST without parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    JSONObject checked_in = (JSONObject) api
            .POST("/appointments/" + appt.getString("appointmentid") + "/checkin");
    System.out.println("Check-in:");
    System.out.println(checked_in.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // DELETE with parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    Map<String, String> delete_params = new HashMap<String, String>();
    delete_params.put("departmentid", "1");
    JSONObject chart_alert = (JSONObject) api.DELETE("/patients/" + new_patient_id + "/chartalert",
            delete_params);
    System.out.println("Removed chart alert:");
    System.out.println(chart_alert.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // DELETE without parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    JSONObject photo = (JSONObject) api.DELETE("/patients/" + new_patient_id + "/photo");
    System.out.println("Removed photo:");
    System.out.println(photo.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // There are no PUTs without parameters
    ////////////////////////////////////////////////////////////////////////////////////////////

    ////////////////////////////////////////////////////////////////////////////////////////////
    // Error conditions
    ////////////////////////////////////////////////////////////////////////////////////////////
    JSONObject bad_path = (JSONObject) api.GET("/nothing/at/this/path");
    System.out.println("GET /nothing/at/this/path:");
    System.out.println(bad_path.toString());
    JSONObject missing_parameters = (JSONObject) api.GET("/appointments/open");
    System.out.println("Missing parameters:");
    System.out.println(missing_parameters.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // Testing token refresh
    //
    // NOTE: this test takes an hour, so it's disabled by default. Change false to true to run.
    ////////////////////////////////////////////////////////////////////////////////////////////
    if (false) {
        String old_token = api.getToken();
        System.out.println("Old token: " + old_token);

        JSONObject before_refresh = (JSONObject) api.GET("/departments");

        // Wait 3600 seconds = 1 hour for token to expire.
        try {
            Thread.sleep(3600 * 1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        JSONObject after_refresh = (JSONObject) api.GET("/departments");

        System.out.println("New token: " + api.getToken());
    }
}