Example usage for org.json JSONArray get

List of usage examples for org.json JSONArray get

Introduction

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

Prototype

public Object get(int index) throws JSONException 

Source Link

Document

Get the object value associated with an index.

Usage

From source file:to.networld.fbtosemweb.fb.FacebookAgentHandler.java

public Vector<FacebookPage> getOwnedPages() throws IOException, JSONException {
    Vector<FacebookPage> resultEntries = new Vector<FacebookPage>();
    JSONObject pagesObject = this.getContent(this.FB_PAGES_URL);
    JSONArray pagesEntries = pagesObject.getJSONArray("data");
    for (int count = 0; count < pagesEntries.length(); count++) {
        JSONObject jsonEntry = (JSONObject) pagesEntries.get(count);
        FacebookPage pagesEntry = new FacebookPage(jsonEntry);
        resultEntries.add(pagesEntry);//from   w w w.  j  av  a 2s  .c om
    }
    return resultEntries;
}

From source file:com.owncloud.android.extensions.ExtensionsListActivity.java

public void done(JSONArray a) {
    LinkedList<HashMap<String, String>> ll = new LinkedList<HashMap<String, String>>();
    for (int i = 0; i < a.length(); ++i) {
        try {/*w w  w . ja  va  2s.com*/
            ExtensionApplicationEntry ela = new ExtensionApplicationEntry(((JSONObject) a.get(i)));
            HashMap<String, String> ss = new HashMap<String, String>();
            ss.put("NAME", ela.getName());
            ss.put("DESC", ela.getDescription());
            ll.add(ss);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    setListAdapter(new SimpleAdapter(this, ll, R.layout.simple_list_item_2, new String[] { "NAME", "DESC" },
            new int[] { android.R.id.text1, android.R.id.text2 }));

}

From source file:com.tinyhydra.botd.GoogleOperations.java

public static List<JavaShop> GetShops(Handler handler, Location currentLocation, String placesApiKey) {
    // Use google places to get all the shops within '500' (I believe meters is the default measurement they use)
    // make a list of JavaShops and pass it to the ListView adapter
    List<JavaShop> shopList = new ArrayList<JavaShop>();
    try {//from   www.  j  av a2  s  .  c om
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        int accuracy = Math.round(currentLocation.getAccuracy());
        if (accuracy < 500)
            accuracy = 500;
        request.setURI(URI.create("https://maps.googleapis.com/maps/api/place/search/json?location="
                + currentLocation.getLatitude() + "," + currentLocation.getLongitude() + "&radius=" + accuracy
                + "&types=" + URLEncoder.encode("cafe|restaurant|food", "UTF-8")
                + "&keyword=coffee&sensor=true&key=" + placesApiKey));
        HttpResponse response = client.execute(request);
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }

        JSONObject predictions = new JSONObject(sb.toString());
        // Google passes back a status string. if we screw up, it won't say "OK". Alert the user.
        String jstatus = predictions.getString("status");
        if (jstatus.equals("ZERO_RESULTS")) {
            Utils.PostToastMessageToHandler(handler, "No shops found in your area.", Toast.LENGTH_SHORT);
            return shopList;
        } else if (!jstatus.equals("OK")) {
            Utils.PostToastMessageToHandler(handler, "Error retrieving local shops.", Toast.LENGTH_SHORT);
            return shopList;
        }

        // This section may fail if there's no results, but we'll just display an empty list.
        //TODO: alert the user and cancel the dialog if this fails
        JSONArray ja = new JSONArray(predictions.getString("results"));

        for (int i = 0; i < ja.length(); i++) {
            JSONObject jo = (JSONObject) ja.get(i);
            shopList.add(new JavaShop(jo.getString("name"), jo.getString("id"), "", jo.getString("reference"),
                    jo.getString("vicinity")));
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return shopList;
}

From source file:ch.icclab.cyclops.persistence.client.InfluxDBClient.java

public TSDBData getData(String query) {
    JSONArray resultArray;
    JSONObject resultObj;/*w  w  w.j a  v  a  2  s . c  o m*/
    TSDBData dataObj = null;
    Representation output;
    ObjectMapper mapper = new ObjectMapper();

    Client client = new Client(Protocol.HTTP);
    ClientResource cr = new ClientResource(url);

    cr.addQueryParameter("q", query);
    cr.addQueryParameter("u", username);
    cr.addQueryParameter("p", password);
    cr.get(MediaType.APPLICATION_JSON);
    output = cr.getResponseEntity();

    try {
        resultArray = new JSONArray(output.getText());
        if (!resultArray.isNull(0)) {
            resultObj = new JSONObject();
            resultObj = (JSONObject) resultArray.get(0);
            dataObj = mapper.readValue(resultObj.toString(), TSDBData.class);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return dataObj;
}

From source file:com.muzima.service.PreferenceService.java

protected List<String> deserialize(String json) {
    if (StringUtils.isEmpty(json))
        return new ArrayList<String>();

    List<String> cohortsList = new ArrayList<String>();
    try {/*  ww  w.j  a  v  a2 s  . com*/
        JSONArray jsonArray = new JSONArray(json);
        for (int i = 0; i < jsonArray.length(); i++) {
            cohortsList.add(jsonArray.get(i).toString());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return cohortsList;
}

From source file:com.inductiveautomation.reporting.examples.datasource.common.RestJsonDataSource.java

/**
 * Creates and returns {@link Dataset} with String column types from a {@link JSONArray}.  Returns empty if no data
 * was found and an exception was not thrown.
 *///from  www .j  av a 2 s .  co  m
private Dataset createDatasetFromJSONArray(JSONArray jsonArray) throws JSONException {
    Dataset ds = null;

    if (jsonArray.length() >= 1) {
        // JSON objects in an array may not have values for each key, so make sure we
        // get the full keyset
        JSONObject reference = findReferenceObjectIndex(jsonArray);

        // get column names from the reference object
        List<String> colNames = new ArrayList<>();
        Iterator keys = reference.keys();
        while (keys.hasNext()) {
            colNames.add(keys.next().toString());
        }

        // now start building dataset to pass into report engine
        DatasetBuilder builder = new DatasetBuilder();
        builder.colNames(colNames.toArray(new String[colNames.size()]));

        // set the column types. We're using all strings in this example, but we could be
        // checking for numeric types and setting different column types to enable calculations
        Class[] types = new Class[colNames.size()];
        for (int i = 0; i < types.length; i++) {
            types[i] = String.class;
        }
        builder.colTypes(types);

        // now create rows for each json list value
        for (int row = 0; row < jsonArray.length(); row++) {
            String[] rowData = new String[colNames.size()];
            for (int col = 0; col < colNames.size(); col++) {
                try {
                    rowData[col] = jsonArray.getJSONObject(row).get(colNames.get(col)).toString();
                } catch (JSONException e) {
                    // ignore because it just means this object didn't have our key
                }
            }
            builder.addRow(rowData);
        }
        ds = builder.build();
    }
    return ds != null ? ds : new BasicDataset();
}

From source file:com.abc.driver.MainActivity.java

/**
 * ??? //from   www.ja va 2  s .c  o m
 * {"result_code":"0","horders":[{"id":6,"shipper_username":
 * "\u674e\u674e\u90bb\u5c45\u5929",
 * "shipper_phone":"","shipper_date":"2015-03-15 00:00:00"
 * ,"shipper_address_code":"110000-110100-110101",
 * "consignee_username":"","consignee_phone"
 * :"","consignee_address_code":"110000-110100-110101",
 * "delivery_time":"0000-00-00 00:00:00"
 * ,"truck_type":"","truck_length":"","cargo_type":"CT1",
 * "cargo_volume":"\u6d4b\u8bd5",
 * "cargo_weight":"\u6d4b\u8bd5\u554a","horder_desc"
 * :"","user_id":9,"status":0, "created_at":"2015-03-15 03:30:50",
 * "updated_at":"2015-03-15 03:30:50"},}]}
 * 
 * @param jsonResult
 */
public void parseJson(JSONObject jsonResult) {
    HashMap<String, Object> mHorder;
    try {
        if (jsonResult.get("horders") != JSONObject.NULL) {
            JSONArray results = jsonResult.getJSONArray("horders");
            if (results.length() < CellSiteConstants.PAGE_COUNT) {
                mHorderTypes[mCurrRadioIdx].hasShowAllHorders = true;
            }

            for (int i = 0; i < results.length(); i++) {
                try {
                    JSONObject resultObj = (JSONObject) results.get(i);
                    mHorder = new HashMap<String, Object>();
                    mHorder.put(CellSiteConstants.SHIPPER_USERNAME,
                            resultObj.getString(CellSiteConstants.SHIPPER_USERNAME));
                    mHorder.put("horder_id", (resultObj).getString(CellSiteConstants.ID));
                    // TODO : 
                    int counter = 0;

                    mHorderTypes[mCurrRadioIdx].nHorders.add(mHorder);
                } catch (Exception e) {
                    mHasExceptionHorder = true;
                    continue;
                }

            }

        }

    } catch (JSONException e) {
        Log.d(TAG, "JSONException" + e.toString());

    }

}

From source file:com.abc.driver.MainActivity.java

/**
 * ??? /*from  w  ww  . j  a  v a  2  s.com*/
 * {"result_code":"0","horders":[{"id":6,"shipper_username":
 * "\u674e\u674e\u90bb\u5c45\u5929",
 * "shipper_phone":"","shipper_date":"2015-03-15 00:00:00"
 * ,"shipper_address_code":"110000-110100-110101",
 * "consignee_username":"","consignee_phone"
 * :"","consignee_address_code":"110000-110100-110101",
 * "delivery_time":"0000-00-00 00:00:00"
 * ,"truck_type":"","truck_length":"","cargo_type":"CT1",
 * "cargo_volume":"\u6d4b\u8bd5",
 * "cargo_weight":"\u6d4b\u8bd5\u554a","horder_desc"
 * :"","user_id":9,"status":0, "created_at":"2015-03-15 03:30:50",
 * "updated_at":"2015-03-15 03:30:50"},}]}
 * 
 * @param jsonResult
 */
public void parseFHorderJson(JSONObject jsonResult) {
    HashMap<String, Object> mHorder;
    try {
        if (jsonResult.get("horders") != JSONObject.NULL) {
            JSONArray results = jsonResult.getJSONArray("horders");
            if (results.length() < CellSiteConstants.PAGE_COUNT) {
                mFHorderTypes.hasShowAllHorders = true;
            }

            for (int i = 0; i < results.length(); i++) {
                try {
                    JSONObject resultObj = (JSONObject) results.get(i);
                    JSONArray repliedDriversObj = null;
                    mHorder = new HashMap<String, Object>();

                    mHorder.put(CellSiteConstants.ALREADY_REPLIED, 0);
                    try {
                        // 1. ???repliedtag 1 ?0
                        // 2.
                        repliedDriversObj = resultObj.getJSONArray(CellSiteConstants.REPLIED_DRIVERS);
                        if (repliedDriversObj != null) {
                            for (int j = 0; j < repliedDriversObj.length(); j++) {
                                String driver_id = ((JSONObject) repliedDriversObj.get(i))
                                        .getString(CellSiteConstants.DRIVER_ID);
                                if (driver_id.equals("" + app.getUser().getId())) {
                                    mHorder.put(CellSiteConstants.ALREADY_REPLIED, 1);
                                    break;
                                }

                            }
                            mHorder.put(CellSiteConstants.REPLIED_DRIVERS_COUNT, repliedDriversObj.length());
                        }
                    } catch (Exception e) {

                    }

                    mHorder.put(CellSiteConstants.SHIPPER_USERNAME,
                            resultObj.getString(CellSiteConstants.SHIPPER_USERNAME));
                    mHorder.put(CellSiteConstants.HORDER_ID, (resultObj).getString(CellSiteConstants.ID));
                    mHorder.put(CellSiteConstants.SHIPPER_PHONE,
                            (resultObj).getString(CellSiteConstants.SHIPPER_PHONE));
                    mHorder.put(CellSiteConstants.USER_ID, (resultObj).getString(CellSiteConstants.USER_ID));

                    CityDBReader dbReader = new CityDBReader(this.getApplicationContext());
                    mHorder.put(CellSiteConstants.SHIPPER_ADDRESS_NAME, dbReader
                            .getNameFromCode((resultObj).getString(CellSiteConstants.SHIPPER_ADDRESS_CODE_IN)));
                    mHorder.put(CellSiteConstants.CONSIGNEE_ADDRESS_NAME, dbReader
                            .getNameFromCode((resultObj).getString(CellSiteConstants.CONSIGNEE_ADDRESS_CODE2)));
                    mHorder.put(CellSiteConstants.CARGO_TYPE,
                            (resultObj).getString(CellSiteConstants.CARGO_TYPE));
                    mHorder.put(CellSiteConstants.CARGO_WEIGHT,
                            (resultObj).getString(CellSiteConstants.CARGO_WEIGHT));
                    mHorder.put(CellSiteConstants.CARGO_VOLUME,
                            (resultObj).getString(CellSiteConstants.CARGO_VOLUME));
                    mHorder.put(CellSiteConstants.TRUCK_TYPE,
                            (resultObj).getString(CellSiteConstants.TRUCK_TYPE));
                    mHorder.put(CellSiteConstants.HORDER_STATUS,
                            (resultObj).getString(CellSiteConstants.STATUS));
                    mHorder.put(CellSiteConstants.SHIPPER_DATE,
                            (resultObj).getString(CellSiteConstants.SHIPPER_DATE));
                    mHorder.put(CellSiteConstants.HORDER_DESCRIPTION,
                            (resultObj).getString(CellSiteConstants.HORDER_DESCRIPTION));
                    mHorder.put(CellSiteConstants.SHIPPER_USERNAME,
                            (resultObj).getString(CellSiteConstants.SHIPPER_USERNAME));

                    // TODO :
                    int counter = 0;

                    mFHorderTypes.nHorders.add(mHorder);
                } catch (Exception e) {
                    mHasExceptionFHorder = true;
                    continue;
                }

            }

        }

    } catch (JSONException e) {
        Log.d(TAG, "JSONException" + e.toString());

    }

}

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

private void testItems(final JSONArray subject) {
    if (allItemSchema != null) {
        for (int i = 0; i < subject.length(); ++i) {
            allItemSchema.validate(subject.get(i));
        }//from ww w.  j ava 2  s .co  m
    } else if (itemSchemas != null) {
        if (!additionalItems && subject.length() > itemSchemas.size()) {
            throw new ValidationException(String.format("expected: [%d] array items, found: [%d]",
                    itemSchemas.size(), subject.length()));
        }
        int itemValidationUntil = Math.min(subject.length(), itemSchemas.size());
        for (int i = 0; i < itemValidationUntil; ++i) {
            itemSchemas.get(i).validate(subject.get(i));
        }
        if (schemaOfAdditionalItems != null) {
            for (int i = itemValidationUntil; i < subject.length(); ++i) {
                schemaOfAdditionalItems.validate(subject.get(i));
            }
        }
    }
}

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

private void testUniqueness(final JSONArray subject) {
    if (subject.length() == 0) {
        return;//w  w w. j a  v  a  2  s  . c o  m
    }
    Collection<Object> uniqueItems = new ArrayList<Object>(subject.length());
    for (int i = 0; i < subject.length(); ++i) {
        Object item = subject.get(i);
        for (Object contained : uniqueItems) {
            if (ObjectComparator.deepEquals(contained, item)) {
                throw new ValidationException("array items are not unique");
            }
        }
        uniqueItems.add(item);
    }
}