List of usage examples for org.json JSONObject putOpt
public JSONObject putOpt(String key, Object value) throws JSONException
From source file:com.trk.aboutme.facebook.SharedPreferencesTokenCachingStrategy.java
private void serializeKey(String key, Bundle bundle, SharedPreferences.Editor editor) throws JSONException { Object value = bundle.get(key); if (value == null) { // Cannot serialize null values. return;//from w w w. j a v a2s.c om } String supportedType = null; JSONArray jsonArray = null; JSONObject json = new JSONObject(); if (value instanceof Byte) { supportedType = TYPE_BYTE; json.put(JSON_VALUE, ((Byte) value).intValue()); } else if (value instanceof Short) { supportedType = TYPE_SHORT; json.put(JSON_VALUE, ((Short) value).intValue()); } else if (value instanceof Integer) { supportedType = TYPE_INTEGER; json.put(JSON_VALUE, ((Integer) value).intValue()); } else if (value instanceof Long) { supportedType = TYPE_LONG; json.put(JSON_VALUE, ((Long) value).longValue()); } else if (value instanceof Float) { supportedType = TYPE_FLOAT; json.put(JSON_VALUE, ((Float) value).doubleValue()); } else if (value instanceof Double) { supportedType = TYPE_DOUBLE; json.put(JSON_VALUE, ((Double) value).doubleValue()); } else if (value instanceof Boolean) { supportedType = TYPE_BOOLEAN; json.put(JSON_VALUE, ((Boolean) value).booleanValue()); } else if (value instanceof Character) { supportedType = TYPE_CHAR; json.put(JSON_VALUE, value.toString()); } else if (value instanceof String) { supportedType = TYPE_STRING; json.put(JSON_VALUE, (String) value); } else if (value instanceof Enum<?>) { supportedType = TYPE_ENUM; json.put(JSON_VALUE, value.toString()); json.put(JSON_VALUE_ENUM_TYPE, value.getClass().getName()); } else { // Optimistically create a JSONArray. If not an array type, we can null // it out later jsonArray = new JSONArray(); if (value instanceof byte[]) { supportedType = TYPE_BYTE_ARRAY; for (byte v : (byte[]) value) { jsonArray.put((int) v); } } else if (value instanceof short[]) { supportedType = TYPE_SHORT_ARRAY; for (short v : (short[]) value) { jsonArray.put((int) v); } } else if (value instanceof int[]) { supportedType = TYPE_INTEGER_ARRAY; for (int v : (int[]) value) { jsonArray.put(v); } } else if (value instanceof long[]) { supportedType = TYPE_LONG_ARRAY; for (long v : (long[]) value) { jsonArray.put(v); } } else if (value instanceof float[]) { supportedType = TYPE_FLOAT_ARRAY; for (float v : (float[]) value) { jsonArray.put((double) v); } } else if (value instanceof double[]) { supportedType = TYPE_DOUBLE_ARRAY; for (double v : (double[]) value) { jsonArray.put(v); } } else if (value instanceof boolean[]) { supportedType = TYPE_BOOLEAN_ARRAY; for (boolean v : (boolean[]) value) { jsonArray.put(v); } } else if (value instanceof char[]) { supportedType = TYPE_CHAR_ARRAY; for (char v : (char[]) value) { jsonArray.put(String.valueOf(v)); } } else if (value instanceof List<?>) { supportedType = TYPE_STRING_LIST; @SuppressWarnings("unchecked") List<String> stringList = (List<String>) value; for (String v : stringList) { jsonArray.put((v == null) ? JSONObject.NULL : v); } } else { // Unsupported type. Clear out the array as a precaution even though // it is redundant with the null supportedType. jsonArray = null; } } if (supportedType != null) { json.put(JSON_VALUE_TYPE, supportedType); if (jsonArray != null) { // If we have an array, it has already been converted to JSON. So use // that instead. json.putOpt(JSON_VALUE, jsonArray); } String jsonString = json.toString(); editor.putString(key, jsonString); } }
From source file:biblivre3.administration.reports.dto.AuthorsSearchResultsDTO.java
@Override public JSONObject toJSONObject(Properties properties) { JSONObject json = new JSONObject(); try {/*from www . j av a 2s.co m*/ json.put("totalPages", this.totalPages); json.put("totalRecords", this.totalRecords); json.put("currentPage", this.currentPage); json.put("recordsPerPage", this.recordsPerPage); for (String key : this.nameIdsPairs.keySet()) { JSONObject result = new JSONObject(); result.putOpt("name", key); result.putOpt("resultRecordIds", nameIdsPairs.get(key).toString()); result.putOpt("size", nameIdsPairs.get(key).size()); json.append("results", result); } } catch (JSONException e) { } return json; }
From source file:app.sunstreak.yourpisd.net.Parser.java
public static JSONArray detailedReport(String html) throws JSONException { Element doc = Jsoup.parse(html); // System.out.println(html); Element assignments = doc.getElementsByAttributeValue("id", "Assignments").get(0); Elements tableRows = assignments.getElementsByTag("tbody").get(0).getElementsByTag("tr"); JSONArray grades = new JSONArray(); for (Element tr : tableRows) { JSONObject assignment = new JSONObject(); Elements columns = tr.getElementsByTag("td"); for (int i = 0; i < columns.size(); i++) { String value = columns.get(i).text(); // do not store empty values! if (value.equals("")) continue; // first try to cast as int. try { assignment.putOpt(assignmentTableHeader(i), Integer.parseInt(value)); // if not int, try double } catch (NumberFormatException e) { try { assignment.putOpt(assignmentTableHeader(i), Double.parseDouble(value)); // if not double, use string } catch (NumberFormatException f) { assignment.putOpt(assignmentTableHeader(i), value); }/*from w ww. j av a 2 s .c om*/ } } String assignmentDetailLink = tr.getElementsByTag("a").get(0).attr("href"); Matcher matcher = Pattern.compile(".+" + "assignmentId=(\\d+)" + "&H=S" + "&GradebookId=(\\d+)" + "&TermId=\\d+" + "&StudentId=\\d+&").matcher(assignmentDetailLink); matcher.find(); int assignmentId = Integer.parseInt(matcher.group(1)); int gradebookId = Integer.parseInt(matcher.group(2)); assignment.put("assignmentId", assignmentId); assignment.put("gradebookId", gradebookId); grades.put(assignment); } // System.out.println((grades)); return grades; }
From source file:app.sunstreak.yourpisd.net.Parser.java
public static Object[] termCategoryGrades(String html) throws JSONException { JSONArray termCategoryGrades = new JSONArray(); Element doc = Jsoup.parse(html); Element categoryTable = doc.getElementById("Category"); Elements rows = categoryTable.getElementsByTag("tbody").get(0).getElementsByTag("tr"); for (Element row : rows) { JSONObject category = new JSONObject(); Elements columns = row.getElementsByTag("td"); for (int i = 0; i < columns.size(); i++) { String value = columns.get(i).text(); // do not store empty values! if (value.equals("")) continue; // first try to cast as int. try { category.putOpt(categoryTableHeader(i), Integer.parseInt(value)); // if not int, try double } catch (NumberFormatException e) { try { category.putOpt(categoryTableHeader(i), Double.parseDouble(value)); // if not double, use string } catch (NumberFormatException f) { category.putOpt(categoryTableHeader(i), value); }//from ww w . j a v a 2 s . c o m } } termCategoryGrades.put(category); } // The average for the six weeks is int average = -1; try { Element finalGrade = doc.getElementById("finalGrade"); average = Integer.parseInt(finalGrade.getElementsByTag("td").get(3).text()); } catch (NullPointerException e) { // Let average be -1 } return new Object[] { termCategoryGrades, average }; }
From source file:m2.android.archetype.example.FacebookSdk.internal.Utility.java
public static Object getStringPropertyAsJSON(JSONObject jsonObject, String key, String nonJSONPropertyKey) throws JSONException { Object value = jsonObject.opt(key); if (value != null && value instanceof String) { JSONTokener tokener = new JSONTokener((String) value); value = tokener.nextValue();/* w w w. j a v a2 s . c om*/ } if (value != null && !(value instanceof JSONObject || value instanceof JSONArray)) { if (nonJSONPropertyKey != null) { // Facebook sometimes gives us back a non-JSON value such as // literal "true" or "false" as a result. // If we got something like that, we present it to the caller as // a GraphObject with a single // property. We only do this if the caller wants that behavior. jsonObject = new JSONObject(); jsonObject.putOpt(nonJSONPropertyKey, value); return jsonObject; } else { throw new FacebookException("Got an unexpected non-JSON object."); } } return value; }
From source file:com.app.swaedes.swaedes.OtherSitePage.java
private void makeRequest() { //Creating JSON Object where data will be stored JSONObject feature = new JSONObject(); JSONObject site = new JSONObject(); try {/*www . java2s . co m*/ //if the user made an audio comment, it will be put with the rest of the data if (bool_audio) { feature.put(Config.KEY_AUDIO, encoded_string_audio); feature.put(Config.KEY_AUDIO_NAME, audio_name); } //Storing data in JSON Object feature.put(Config.KEY_WATER, water); feature.put(Config.KEY_LARVAE, larvae); feature.put(Config.KEY_COMMENT, comment); feature.put(Config.KEY_CLOTHES, nb_clothes); feature.put(Config.KEY_BOXES, nb_boxes); feature.put(Config.KEY_LATITUDE, latitude); feature.put(Config.KEY_LONGITUDE, longitude); feature.put(Config.KEY_IMAGE, encoded_string_image); feature.put(Config.KEY_USER, user); feature.put(Config.KEY_IMAGE_NAME, image_name); site.put(Config.KEY_ADDRESS, address); site.put(Config.KEY_SITE_NAME, name); site.put(Config.KEY_BOOL_CONSTRUCTION_SITE, true); site.put(Config.KEY_SITE_TYPE, keyword); feature.putOpt(Config.KEY_SITE, site); Log.d("Swaedes", feature.toString()); //Creating a new JSON Object request to be sent JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, Config.UPLOAD_URL, feature, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { //if the response is success, launches the main menu if (response.toString().contains(Config.UPLOAD_SUCCESS)) { Intent intent = new Intent(OtherSitePage.this, MainMenuPage.class); startActivity(intent); } else { Toast.makeText(OtherSitePage.this, "Error, try again", Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }) { //setting the headers of the request @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json; charset=utf-8"); return headers; } }; //Getting the request queue of the app, adding the request to it Swaedes swaedes = (Swaedes) getApplication(); RequestQueue mVolleyRequestQueue = swaedes.getVolleyRequestQueue(); mVolleyRequestQueue.add(request); } catch (JSONException e) { Log.e("Swaedes", "Could not parse malformed JSON: \"" + feature + "\""); } }
From source file:com.clover.sdk.v3.JsonHelper.java
public static Object toJSON(Object object) { if (object instanceof Map) { JSONObject json = new JSONObject(); Map map = (Map) object; for (Object key : map.keySet()) { try { json.putOpt(key.toString(), toJSON(map.get(key))); } catch (JSONException e) { /* ignore for now */ } }// w w w. ja v a 2s . co m return json; } else if (object instanceof Iterable) { JSONArray json = new JSONArray(); for (Object value : ((Iterable) object)) { json.put(value); } return json; } else if (object instanceof Enum) { return ((Enum) object).name(); } else { return object; } }
From source file:com.app.swaedes.swaedes.SignUpPage.java
private void register() { //getting all the values filled by the new user String gender = ""; if (male.isChecked()) gender = "M"; else if (female.isChecked()) gender = "F"; final String provinces = province.getSelectedItem().toString(); final String emails = email.getText().toString(); final String ages = age.getText().toString(); final String passwords = password.getText().toString(); final String confirm_passwords = confirm_password.getText().toString(); //Check if no values are missing if (!gender.equals("") && !emails.equals("") && !passwords.equals("") && !ages.equals("")) { //Cast the age as an integer final int int_age = Integer.parseInt(ages); //Check if email address is valid if (Config.isEmailValid(emails)) { //Check if passwords matches if (passwords.equals(confirm_passwords)) { if (passwords.length() >= 8) { /** Creating JSON Objects where the data * where the data will be stored. * The format of the object must be * the same as the one on the server *///from w w w. j a v a 2s .c o m JSONObject user = new JSONObject(); JSONObject extend_user = new JSONObject(); JSONObject province = new JSONObject(); try { user.put(Config.KEY_EMAIL, emails); user.put(Config.KEY_PASSWORD, passwords); extend_user.put(Config.KEY_AGE, int_age); extend_user.put(Config.KEY_GENDER, gender); province.put(Config.KEY_PROVINCE_NAME, provinces); extend_user.putOpt(Config.KEY_PROVINCE, province); user.putOpt(Config.KEY_EXTEND_USER, extend_user); Log.d("Swaedes", user.toString()); //Creates a new JSON object request with Volley JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, Config.REGISTER_URL, user, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { //If we are getting success from server if (response.toString().contains(Config.REGISTER_SUCCESS)) { Toast.makeText(SignUpPage.this, "Successfully registered", Toast.LENGTH_SHORT).show(); } else { //If the server response is not success //Displaying an error message on toast Toast.makeText(SignUpPage.this, "User already registered", Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }) { //sets the request headers @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json; charset=utf-8"); return headers; } }; //adds the request to the request queue Swaedes swaedes = (Swaedes) getApplication(); RequestQueue mVolleyRequestQueue = swaedes.getVolleyRequestQueue(); mVolleyRequestQueue.add(request); } catch (JSONException e) { Log.e("Swaedes", "Could not parse malformed JSON: \"" + user + "\""); } } //if password is not long enough else { Toast.makeText(SignUpPage.this, "Password must contain at least 8 characters", Toast.LENGTH_SHORT).show(); } } //if passwords don't match else { Toast.makeText(SignUpPage.this, "Passwords don't match", Toast.LENGTH_SHORT).show(); } } //if email address is not valid else { Toast.makeText(SignUpPage.this, "Enter a valid email address", Toast.LENGTH_SHORT).show(); } } //if data is missing else { Toast.makeText(SignUpPage.this, "Please fill all the informations", Toast.LENGTH_SHORT).show(); } }
From source file:edu.umass.cs.gigapaxos.paxospackets.RequestPacket.java
@Override public JSONObject toJSONObjectImpl() throws JSONException { JSONObject json = new JSONObject(); json.put(Keys.QID.toString(), this.requestID); json.put(Keys.QV.toString(), this.requestValue); json.putOpt(Keys.RV.toString(), this.responseValue); json.put(Keys.ET.toString(), this.entryTime); if (forwardCount > 0) json.put(Keys.NFWDS.toString(), this.forwardCount); if (this.stop) json.put(Keys.STOP.toString(), this.stop); if (DEBUG) {/*w w w . j a va 2 s .co m*/ json.put(RequestPacket.Keys.FWDR.toString(), this.forwarderID); json.putOpt(Keys.DBG.toString(), this.debugInfo); } json.put(PaxosPacket.NodeIDKeys.E.toString(), this.entryReplica); if (this.clientAddress != null) json.put(Keys.CA.toString(), this.clientAddress); if (this.listenAddress != null) json.put(Keys.LA.toString(), this.listenAddress); if (this.shouldReturnRequestValue) json.put(Keys.QF.toString(), this.shouldReturnRequestValue); // convert latched along batch to json array if (this.batched != null && this.batched.length > 0) { JSONArray batchedJSON = new JSONArray(); for (int i = 0; i < this.batched.length; i++) { batchedJSON.put(this.batched[i].toJSONObject()); // batchedJSON.put(this.batched[i].toString()); } json.put(Keys.BATCH.toString(), batchedJSON); } // digest related parameters if (this.broadcasted) json.put(Keys.BC.toString(), this.broadcasted); if (this.digest != null) try { json.put(Keys.DIG.toString(), new String(this.digest, CHARSET)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return json; }
From source file:biblivre3.circulation.UserDTO.java
@Override public JSONObject toJSONObject(Properties properties) { JSONObject json = new JSONObject(); try {//w ww . j av a 2 s .c o m json.putOpt("name", this.getName()); json.putOpt("userStatus", this.getUserStatus()); json.putOpt("userid", this.getUserid()); json.putOpt("signup_date", this.getSignup_date()); json.putOpt("alter_date", this.getAlter_date()); json.putOpt("renew_date", this.getRenew_date()); json.putOpt("social_id_number", this.getSocial_id_number()); json.putOpt("dlicense", this.getDlicense()); json.putOpt("type_id", this.getTypeId()); json.putOpt("birthday", this.getBirthday()); json.putOpt("marital_status", this.getMarital_status()); json.putOpt("sex", this.getSex()); json.putOpt("occupation", this.getOccupation()); json.putOpt("father_name", this.getFather_name()); json.putOpt("mother_name", this.getMother_name()); json.putOpt("reference_1", this.getReference_1()); json.putOpt("tel_ref_1", this.getTelRef1()); json.putOpt("reference_2", this.getReference_2()); json.putOpt("tel_ref_2", this.getTelRef2()); json.putOpt("email", this.getEmail()); json.putOpt("user_type", this.getUserType()); UserTypeDTO type = new CirculationBO().getUserTypeById(this.getUserType()); json.putOpt("user_type_text", type != null ? type.getName() : ""); json.putOpt("obs", this.getObs()); json.putOpt("country", this.getCountry()); json.putOpt("state", this.getState()); json.putOpt("city", this.getCity()); json.putOpt("address", this.getAddress()); json.putOpt("number", this.getNumber()); json.putOpt("completion", this.getCompletion()); json.putOpt("zip_code", this.getZip_code()); json.putOpt("photo_id", this.getPhoto()); json.putOpt("whosignup", this.getWhosignup()); json.putOpt("loginid", this.getLoginid()); json.putOpt("cellphone", this.getCellphone()); json.putOpt("extension_line", this.getExtension_line()); json.putOpt("login", this.getLoginName()); json.putOpt("card_number", this.getCardNumber()); json.putOpt("has_card", StringUtils.isNotBlank(this.getCardNumber())); if (this.getTotalFines() != null && this.getTotalFines() > 0) { json.putOpt("total_fines", this.getTotalFines()); } } catch (JSONException e) { } return json; }