Example usage for org.json JSONArray getJSONObject

List of usage examples for org.json JSONArray getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(int index) throws JSONException 

Source Link

Document

Get the JSONObject associated with an index.

Usage

From source file:com.googlecode.CallerLookup.Main.java

public void parseLookupEntries() {
    mLookupEntries = new HashMap<String, LookupEntry>();
    mUserLookupEntries = new HashMap<String, LookupEntry>();

    boolean updateFound = false;
    for (String fileName : getApplicationContext().fileList()) {
        if (fileName.equals(UPDATE_FILE)) {
            try {
                FileInputStream file = getApplicationContext().openFileInput(UPDATE_FILE);
                XmlPullParser xml = Xml.newPullParser();
                xml.setInput(file, null);
                parseLookupEntries(xml, mLookupEntries);
                file.close();/*from w  w w  .jav  a2 s  .co  m*/
                updateFound = true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (fileName.equals(SAVED_FILE)) {
            try {
                FileInputStream file = getApplicationContext().openFileInput(SAVED_FILE);
                InputStreamReader reader = new InputStreamReader(file);
                char[] content = new char[8000];
                reader.read(content);
                JSONArray userLookupEntries = new JSONArray(new String(content));
                int count = userLookupEntries.length();
                for (int i = 0; i < count; i++) {
                    JSONObject userLookupEntry = userLookupEntries.getJSONObject(i);
                    mUserLookupEntries.put(userLookupEntry.getString("name"), new LookupEntry(userLookupEntry));
                }
                file.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    if (!updateFound) {
        XmlResourceParser xml = getApplicationContext().getResources().getXml(R.xml.lookups);
        parseLookupEntries(xml, mLookupEntries);
        xml.close();
    }
}

From source file:ti.mobileapptracker.MobileapptrackerModule.java

private List<MATEventItem> convertToMATEventItems(Object[] arrItemMaps) {
    List<MATEventItem> listItems = new ArrayList<MATEventItem>();

    try {/* ww  w . j  a  v  a 2  s . c o  m*/
        JSONArray arr = new JSONArray(Arrays.toString(arrItemMaps));

        for (int i = 0; i < arr.length(); i++) {
            JSONObject item = arr.getJSONObject(i);

            String itemName = item.getString("item");
            int quantity = 0;
            double unitPrice = 0;
            double revenue = 0;
            String attribute1 = null;
            String attribute2 = null;
            String attribute3 = null;
            String attribute4 = null;
            String attribute5 = null;

            if (item.has("quantity")) {
                quantity = item.getInt("quantity");
            }
            if (item.has("unit_price")) {
                unitPrice = item.getDouble("unit_price");
            }
            if (item.has("revenue")) {
                revenue = item.getDouble("revenue");
            }

            if (item.has("attribute_sub1")) {
                attribute1 = item.getString("attribute_sub1");
            }
            if (item.has("attribute_sub2")) {
                attribute2 = item.getString("attribute_sub2");
            }
            if (item.has("attribute_sub3")) {
                attribute3 = item.getString("attribute_sub3");
            }
            if (item.has("attribute_sub4")) {
                attribute4 = item.getString("attribute_sub4");
            }
            if (item.has("attribute_sub5")) {
                attribute5 = item.getString("attribute_sub5");
            }

            MATEventItem eventItem = new MATEventItem(itemName, quantity, unitPrice, revenue, attribute1,
                    attribute2, attribute3, attribute4, attribute5);
            listItems.add(eventItem);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return listItems;
}

From source file:org.everit.json.schema.IntegrationTest.java

@Parameters(name = "{2}")
public static List<Object[]> params() {
    List<Object[]> rval = new ArrayList<>();
    Reflections refs = new Reflections("org.everit.json.schema.draft4", new ResourcesScanner());
    Set<String> paths = refs.getResources(Pattern.compile(".*\\.json"));
    for (String path : paths) {
        if (path.indexOf("/optional/") > -1 || path.indexOf("/remotes/") > -1) {
            continue;
        }//from   w w  w. j av  a  2  s .c o m
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        JSONArray arr = loadTests(IntegrationTest.class.getResourceAsStream("/" + path));
        for (int i = 0; i < arr.length(); ++i) {
            JSONObject schemaTest = arr.getJSONObject(i);
            JSONArray testcaseInputs = schemaTest.getJSONArray("tests");
            for (int j = 0; j < testcaseInputs.length(); ++j) {
                JSONObject input = testcaseInputs.getJSONObject(j);
                Object[] params = new Object[5];
                params[0] = "[" + fileName + "]/" + schemaTest.getString("description");
                params[1] = schemaTest.get("schema");
                params[2] = "[" + fileName + "]/" + input.getString("description");
                params[3] = input.get("data");
                params[4] = input.getBoolean("valid");
                rval.add(params);
            }
        }
    }
    return rval;
}

From source file:com.dzt.uberclone.HomeFragment.java

private void showUberMarkers(String json) {
    try {//from  w w  w  .ja va2 s .c om
        markers.clear();
        shortestTime = 0;
        JSONArray jsonArray = new JSONArray(json);
        nearbyUbers = jsonArray.length();
        ubercount = 0;
        if (nearbyUbers == 0) {
            displayNoUbersMessage();
        }
        for (int i = 0; i < nearbyUbers; i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            double lat = jsonObject.getDouble("pos_lat");
            double lon = jsonObject.getDouble("pos_long");
            addUberMarker(lat, lon);
            getShortestTime(lat, lon);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:org.matrix.console.store.LoginStorage.java

/**
 * Return a list of HomeserverConnectionConfig.
 * @return a list of HomeserverConnectionConfig.
 *//*w ww  .j a  v  a 2s .  c  o m*/
public ArrayList<HomeserverConnectionConfig> getCredentialsList() {
    SharedPreferences prefs = mContext.getSharedPreferences(PREFS_LOGIN, Context.MODE_PRIVATE);

    String connectionConfigsString = prefs.getString(PREFS_KEY_CONNECTION_CONFIGS, null);

    Log.d(LOG_TAG, "Got connection json: " + connectionConfigsString);

    if (connectionConfigsString == null) {
        return new ArrayList<HomeserverConnectionConfig>();
    }

    try {

        JSONArray connectionConfigsStrings = new JSONArray(connectionConfigsString);

        ArrayList<HomeserverConnectionConfig> configList = new ArrayList<HomeserverConnectionConfig>(
                connectionConfigsStrings.length());

        for (int i = 0; i < connectionConfigsStrings.length(); i++) {
            configList.add(HomeserverConnectionConfig.fromJson(connectionConfigsStrings.getJSONObject(i)));
        }

        return configList;
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Failed to deserialize accounts " + e.getMessage(), e);
        throw new RuntimeException("Failed to deserialize accounts");
    }
}

From source file:com.krayzk9s.imgurholo.ui.CommentsFragment.java

private void addComments(JSONObject comments) {
    try {/*  w ww.j a v a  2  s . co  m*/
        commentDataArray = new ArrayList<JSONParcelable>();
        JSONArray data = comments.getJSONArray("data");
        for (int i = 0; i < data.length(); i++) {
            JSONObject message = data.getJSONObject(i);
            JSONParcelable dataParcel = new JSONParcelable();
            dataParcel.setJSONObject(message);
            commentDataArray.add(dataParcel);
        }
        commentsAdapter.addAll(commentDataArray);
    } catch (JSONException e) {
        errorText.setVisibility(View.VISIBLE);
        errorText.setText("Error getting comments");
        Log.e("Error!", "adding messages" + e.toString());
    }
    mDrawerList.setAdapter(commentsAdapter);
    commentsAdapter.notifyDataSetChanged();
}

From source file:com.amazon.android.contentbrowser.helper.AuthHelper.java

/**
 * Retrieves the list of possible MVPD providers from the URL found at R.string.mvpd_url in
 * custom.xml and gives them to ContentBrowser.
 *//*from  ww  w .ja  v  a  2s . c  o m*/
public void setupMvpdList() {

    try {

        String mvpdUrl = mAppContext.getResources().getString(R.string.mvpd_url);

        // The user has no MVPD URL set up.
        if (mvpdUrl.equals(DEFAULT_MVPD_URL)) {
            Log.d(TAG, "MVPD feature not used.");
            return;
        }
        String jsonStr = NetworkUtils.getDataLocatedAtUrl(mvpdUrl);

        JSONObject json = new JSONObject(jsonStr);
        JSONArray mvpdWhiteList = json.getJSONArray(MVPD_WHITE_LIST);

        for (int i = 0; i < mvpdWhiteList.length(); i++) {

            JSONObject mvpdItem = mvpdWhiteList.getJSONObject(i);
            mContentBrowser.addPoweredByLogoUrlByName(mvpdItem.getString(PreferencesConstants.MVPD_LOGO_URL),
                    mvpdItem.getString(LOGGED_IN_IMAGE));
        }

    } catch (Exception e) {
        Log.e(TAG, "Get MVPD logo urls failed!!!", e);

    }
}

From source file:org.wso2.carbon.connector.integration.test.googleanalytics.GoogleanalyticsConnectorIntegrationTest.java

/**
 * Positive test case for createAccountUserLink method with mandatory parameters.
 *
 * @throws org.json.JSONException/*from w  ww. j  ava2  s. c  o  m*/
 * @throws java.io.IOException
 */
@Test(groups = {
        "wso2.esb" }, description = "googleanalytics {createAccountUserLink} integration test with mandatory parameters.", dependsOnMethods = {
                "testListAccountSummariesWithMandatoryParameters" })
public void testCreateAccountUserLinkWithMandatoryParameters() throws IOException, JSONException {

    esbRequestHeadersMap.put("Action", "urn:createAccountUserLink");
    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_createAccountUserLink_mandatory.json");

    final JSONObject esbResponse = esbRestResponse.getBody();

    final String userLinkId = esbResponse.getString("id");
    connectorProperties.put("userLinkId", userLinkId);

    final String apiEndpoint = apiEndpointUrl + "/management/accounts/"
            + connectorProperties.getProperty("accountId") + "/entityUserLinks";
    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndpoint, "GET", apiRequestHeadersMap);

    final JSONArray itemArray = apiRestResponse.getBody().getJSONArray("items");

    String id;
    String email = "";
    String permissions = "";
    String selfLink = "";
    for (int i = 0; i < itemArray.length(); i++) {
        id = itemArray.getJSONObject(i).getString("id");
        if (id.equals(userLinkId)) {
            permissions = itemArray.getJSONObject(i).getJSONObject("permissions").toString();
            email = itemArray.getJSONObject(i).getJSONObject("userRef").getString("email");
            selfLink = itemArray.getJSONObject(i).getString("selfLink");
            break;
        }
    }

    Assert.assertEquals(connectorProperties.getProperty("userLinkEmail"), email);
    Assert.assertEquals(esbResponse.getJSONObject("permissions").toString(), permissions);
    Assert.assertEquals(esbResponse.getString("selfLink"), selfLink);
}

From source file:org.wso2.carbon.connector.integration.test.googleanalytics.GoogleanalyticsConnectorIntegrationTest.java

/**
 * Positive test case for updateAccountUserLink method with mandatory parameters.
 *
 * @throws org.json.JSONException/*from  w  w  w  . ja va 2 s.c  o  m*/
 * @throws java.io.IOException
 */
@Test(groups = {
        "wso2.esb" }, description = "googleanalytics {updateAccountUserLink} integration test with mandatory parameters.", dependsOnMethods = {
                "testCreateAccountUserLinkWithMandatoryParameters",
                "testListAccountSummariesWithMandatoryParameters" })
public void testUpdateAccountUserLinkWithMandatoryParameters() throws IOException, JSONException {

    final String apiEndpoint = apiEndpointUrl + "/management/accounts/"
            + connectorProperties.getProperty("accountId") + "/entityUserLinks";
    RestResponse<JSONObject> apiRestResponseBefore = sendJsonRestRequest(apiEndpoint, "GET",
            apiRequestHeadersMap);
    final String userLinkId = connectorProperties.getProperty("userLinkId");
    final JSONArray itemArrayBefore = apiRestResponseBefore.getBody().getJSONArray("items");

    String id;
    String permissions = "";
    for (int i = 0; i < itemArrayBefore.length(); i++) {
        id = itemArrayBefore.getJSONObject(i).getString("id");
        if (id.equals(userLinkId)) {
            permissions = itemArrayBefore.getJSONObject(i).getJSONObject("permissions").toString();
            break;
        }
    }

    esbRequestHeadersMap.put("Action", "urn:updateAccountUserLink");
    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_updatedAccountUserLink_mandatory.json");

    final JSONObject esbResponse = esbRestResponse.getBody();

    RestResponse<JSONObject> apiRestResponseAfter = sendJsonRestRequest(apiEndpoint, "GET",
            apiRequestHeadersMap);

    final JSONArray itemArrayAfter = apiRestResponseAfter.getBody().getJSONArray("items");

    String idAfter;
    String permissionsAfter = "";
    for (int i = 0; i < itemArrayAfter.length(); i++) {
        idAfter = itemArrayAfter.getJSONObject(i).getString("id");
        if (idAfter.equals(userLinkId)) {
            permissionsAfter = itemArrayAfter.getJSONObject(i).getJSONObject("permissions").toString();
            break;
        }
    }

    Assert.assertNotEquals(permissions, permissionsAfter);
    Assert.assertEquals(esbResponse.getJSONObject("permissions").toString(), permissionsAfter);
}

From source file:com.liferay.mobile.android.v7.journalfolder.JournalFolderService.java

public JSONObject getFolder(long folderId) throws Exception {
    JSONObject _command = new JSONObject();

    try {/*from  w w  w.j  a v  a  2  s  .c  om*/
        JSONObject _params = new JSONObject();

        _params.put("folderId", folderId);

        _command.put("/journal.journalfolder/get-folder", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONObject(0);
}