List of usage examples for org.json JSONArray length
public int length()
From source file:br.com.indigo.android.facebook.SocialFacebook.java
private void handleEventsResponse(JSONObject jsonResponse, EventsListener listener) { ArrayList<FbEvent> events = new ArrayList<FbEvent>(); try {/*from w w w . j a va 2 s .c o m*/ JSONArray objs = jsonResponse.getJSONArray("data"); for (int i = 0; i < objs.length(); i++) { JSONObject obj = objs.getJSONObject(i); events.add(parseEvent(obj)); } String nextPage = null; JSONObject paging = jsonResponse.optJSONObject("paging"); if (paging != null) { nextPage = paging.optString("next"); } listener.onComplete(events, nextPage); } catch (JSONException e) { Util.logd(TAG, "Could not parse Json response", e); listener.onFail(e); } }
From source file:br.com.indigo.android.facebook.SocialFacebook.java
private void handleCommentsResponse(JSONObject jsonResponse, CommentsListener listener) { FbComment comment = null;//from w w w . j a v a 2s . c om ArrayList<FbComment> comments = new ArrayList<FbComment>(); try { JSONArray objs = jsonResponse.getJSONArray("data"); for (int i = 0; i < objs.length(); i++) { JSONObject obj = objs.getJSONObject(i); comment = new FbComment(); comment.setId(obj.getString("id")); comment.setMessage(obj.optString("message")); comment.setCreatedTime(new Date(obj.optLong("created_time") * 1000)); comment.setNumberOfLikes(obj.optInt("likes")); JSONObject fromJson = obj.optJSONObject("from"); if (fromJson != null) { FbSimpleUser fromUser = new FbSimpleUser(); fromUser.setId(fromJson.getString("id")); fromUser.setName(fromJson.optString("name")); comment.setFrom(fromUser); } comments.add(comment); } String nextPage = null; JSONObject paging = jsonResponse.optJSONObject("paging"); if (paging != null) { nextPage = paging.optString("next"); } listener.onComplete(comments, nextPage); } catch (JSONException e) { Util.logd(TAG, "Could not parse Json response", e); listener.onFail(e); } }
From source file:com.ledger.android.u2f.bridge.MainActivity.java
private U2FContext parseU2FContextSign(JSONObject json) { try {/*from w w w. j av a 2 s . c o m*/ 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 va 2s .c o m 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);//from w w w. j a v a2s . c o m 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:edu.txstate.dmlab.clusteringwiki.sources.AbsSearchResultCol.java
/** * Creates a collection of results from JSON response * Note that firstPosition must be set before adding * results as result ids depend on that value. * @param res//from www . j a va 2 s . c om */ public AbsSearchResultCol(JSONObject res) { if (res == null) return; JSONObject search = null; try { search = res.getJSONObject("search"); JSONArray errors = search.getJSONArray("errors"); if (errors != null && errors.length() > 0) { for (int i = 0; i < errors.length(); i++) { String error = errors.getString(i); addError("AbS API exception: " + error); } return; } } catch (JSONException e) { addError("AbS API exception: " + e.getMessage()); } try { totalResults = search.getInt("totalResults"); firstPosition = search.getInt("firstPosition"); JSONArray j = search.getJSONArray("results"); returnedCount = j.length(); for (int i = 0; i < j.length(); i++) { ICWSearchResult r = new AbsSearchResult(j.getJSONObject(i)); r.setIndex(i); addResult(r); } } catch (JSONException e) { addError("Could not retrieve AbS results: " + e.getMessage()); } }
From source file:test.Testing.java
public static void main(String[] args) throws Exception { //////////////////////////////////////////////////////////////////////////////////////////// // Setup/*from ww w . j ava 2 s. c o 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()); } }
From source file:re.notifica.cordova.NotificarePlugin.java
/** * Register a device and (optionally) its user to Notificare * @param args//w ww . j ava2 s . co m * @param callbackContext * @throws JSONException */ protected void registerDevice(JSONArray args, final CallbackContext callbackContext) { Log.d(TAG, "REGISTER"); try { String deviceId = args.getString(0); String userId = null; String userName = null; if (args.length() == 2) { userId = args.getString(1); } if (args.length() == 3) { userId = args.getString(1); userName = args.getString(2); } Notificare.shared().registerDevice(deviceId, userId, userName, new NotificareCallback<String>() { @Override public void onSuccess(String result) { Notificare.shared().setDeviceId(result); if (callbackContext == null) { return; } callbackContext.success(); } @Override public void onError(NotificareError error) { if (callbackContext == null) { return; } callbackContext.error(error.getLocalizedMessage()); } }); } catch (JSONException e) { callbackContext.error("JSON parse error"); } }
From source file:re.notifica.cordova.NotificarePlugin.java
/** * Add tags to a device//from w ww . j a va 2s . co m * @param args * @param callbackContext */ protected void addDeviceTags(JSONArray args, final CallbackContext callbackContext) { Log.d(TAG, "ADDTAGS"); ArrayList<String> tagList = new ArrayList<String>(); try { JSONArray tags = args.getJSONArray(0); if (tags != null) { for (int i = 0; i < tags.length(); i++) { tagList.add(tags.getString(i)); } } Notificare.shared().addDeviceTags(tagList, new NotificareCallback<Boolean>() { @Override public void onSuccess(Boolean result) { if (callbackContext == null) { return; } callbackContext.success(); } @Override public void onError(NotificareError error) { if (callbackContext == null) { return; } callbackContext.error(error.getLocalizedMessage()); } }); } catch (JSONException e) { callbackContext.error("JSON parse error"); } }
From source file:re.notifica.cordova.NotificarePlugin.java
/** * Create a new user account//from w w w .j a v a 2 s.c om * @param args * @param callbackContext */ protected void createAccount(JSONArray args, final CallbackContext callbackContext) { Log.d(TAG, "CREATEACCOUNT"); try { String email = args.getString(0); String password = args.getString(1); String userName = null; if (args.length() == 3) { userName = args.optString(2); } Notificare.shared().createAccount(email, password, userName, new NotificareCallback<Boolean>() { @Override public void onSuccess(Boolean result) { if (callbackContext == null) { return; } callbackContext.success(); } @Override public void onError(NotificareError error) { if (callbackContext == null) { return; } callbackContext.error(error.getLocalizedMessage()); } }); } catch (JSONException e) { callbackContext.error("JSON parse error"); } }