List of usage examples for org.json JSONObject optString
public String optString(String key)
From source file:com.yanzhenjie.nohttp.HttpHeaders.java
@Override public void setJSONString(String jsonString) throws JSONException { clear();/*from ww w . j a v a 2s .c o m*/ JSONObject jsonObject = new JSONObject(jsonString); Iterator<String> keySet = jsonObject.keys(); while (keySet.hasNext()) { String key = keySet.next(); String value = jsonObject.optString(key); JSONArray values = new JSONArray(value); for (int i = 0; i < values.length(); i++) add(key, values.optString(i)); } }
From source file:org.b3log.solo.event.symphony.CommentSender.java
@Override public void action(final Event<JSONObject> event) throws EventException { final JSONObject data = event.getData(); LOGGER.log(Level.FINER, "Processing an event[type={0}, data={1}] in listener[className={2}]", new Object[] { event.getType(), data, ArticleSender.class.getName() }); try {//from w w w.j a v a 2s . c o m final JSONObject originalComment = data.getJSONObject(Comment.COMMENT); final JSONObject preference = preferenceQueryService.getPreference(); if (null == preference) { throw new EventException("Not found preference"); } final String blogHost = preference.getString(Preference.BLOG_HOST).toLowerCase(); if (blogHost.contains("localhost")) { LOGGER.log(Level.INFO, "Blog Solo runs on local server, so should not send this comment[id={0}] to Symphony", new Object[] { originalComment.getString(Keys.OBJECT_ID) }); return; } final HTTPRequest httpRequest = new HTTPRequest(); httpRequest.setURL(ADD_COMMENT_URL); httpRequest.setRequestMethod(HTTPRequestMethod.PUT); final JSONObject requestJSONObject = new JSONObject(); final JSONObject comment = new JSONObject(); comment.put("commentId", originalComment.optString(Keys.OBJECT_ID)); comment.put("commentAuthorName", originalComment.getString(Comment.COMMENT_NAME)); comment.put("commentAuthorEmail", originalComment.getString(Comment.COMMENT_EMAIL)); comment.put(Comment.COMMENT_CONTENT, originalComment.getString(Comment.COMMENT_CONTENT)); comment.put("articleId", originalComment.getString(Comment.COMMENT_ON_ID)); requestJSONObject.put(Comment.COMMENT, comment); requestJSONObject.put("clientVersion", SoloServletListener.VERSION); requestJSONObject.put("clientRuntimeEnv", Latkes.getRuntimeEnv().name()); requestJSONObject.put("clientName", "B3log Solo"); requestJSONObject.put("clientHost", blogHost); requestJSONObject.put("clientAdminEmail", preference.optString(Preference.ADMIN_EMAIL)); requestJSONObject.put("userB3Key", preference.optString(Preference.KEY_OF_SOLO)); httpRequest.setPayload(requestJSONObject.toString().getBytes("UTF-8")); urlFetchService.fetchAsync(httpRequest); } catch (final Exception e) { LOGGER.log(Level.SEVERE, "Sends a comment to Symphony error: {0}", e.getMessage()); } LOGGER.log(Level.FINER, "Sent a comment to Symphony"); }
From source file:com.util.httpAccount.java
public Account getAccountObject(String tel) { String telefono = tel.replace("-", ""); System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON"); //String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json"; String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/" + telefono + ".json"; System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null;//from www .j ava2 s . com Account account = new Account(); try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } String jsonResult = sb.toString(); // System.out.println(sb.toString()); //System.out.println("\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n"); JSONObject objJason = new JSONObject(jsonResult); JSONArray dataJson = new JSONArray(); dataJson = objJason.getJSONArray("data"); //System.out.println("objeto normal 1 "+dataJson.toString()); // // // System.out.println("\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n"); String jsonString2 = dataJson.toString(); String temp = dataJson.toString(); temp = jsonString2.replace("[", ""); jsonString2 = temp.replace("]", ""); // System.out.println("new json string"+jsonString2); JSONObject objJson2 = new JSONObject(jsonString2); // System.out.println("el objeto simple json es " + objJson2.toString()); // System.out.println("\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n"); String account1 = objJson2.optString("account"); // System.out.println(account1); JSONObject objJson3 = new JSONObject(account1); // System.out.println("el ULTIMO OBJETO SIMPLE ES " + objJson3.toString()); // System.out.println("\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n"); String firstName = objJson3.getString("first_name"); System.out.println(firstName); System.out.println(objJson3.get("language_id")); // System.out.println("\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n"); Gson gson = new Gson(); account = gson.fromJson(objJson3.toString(), Account.class); //System.out.println(account.getFirst_name()); // System.out.println(account.getCreation()); account.setLanguaje_id(objJson3.get("language_id").toString()); account.setId(objJson3.get("id").toString()); account.setBalance(objJson3.get("balance").toString()); System.out.println("el id del account es " + account.getId()); } else { System.out.print("no se pudo conectar con el servidor"); account = null; } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } return account; }
From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java
/** * Read labels into label map/* w ww . jav a 2 s . c om*/ * @param userCrxId * @param dashboardId * @throws JSONException * @throws ApiServiceException * @throws IOException */ private void readLabels(JSONArray labels, String userCrxId) throws JSONException, ApiServiceException, IOException { for (int i = 0; i < labels.length(); i++) { JSONObject label = labels.getJSONObject(i); putLabelIntoCache(label); String contactId = label.optString("contact_id"); if (userCrxId.equals(contactId)) { Preferences.setString(OpencrxUtilities.PREF_RESOURCE_ID, label.getString("id")); } } }
From source file:com.google.blockly.model.FieldDate.java
public static FieldDate fromJson(JSONObject json) throws BlockLoadingException { String name = json.optString("name"); if (TextUtils.isEmpty(name)) { throw new BlockLoadingException("field_date \"name\" attribute must not be empty."); }/*from www .ja va 2 s . c om*/ FieldDate field = new FieldDate(name); String dateStr = json.optString("date"); if (!TextUtils.isEmpty(dateStr) && !field.setFromString(dateStr)) { throw new BlockLoadingException("Unable to parse date: " + dateStr); } return field; }
From source file:fr.openbike.android.io.RemoteStationsUpdateHandler.java
/** {@inheritDoc} */ @Override//w ww. java2s .c om public Object parse(JSONObject jsonBikes, OpenBikeDBAdapter dbAdapter) throws JSONException, IOException { long version = jsonBikes.getLong(VERSION); String message = jsonBikes.optString(MESSAGE); JSONArray stations = jsonBikes.optJSONArray(STATIONS); if (stations != null) { dbAdapter.cleanAndInsertStations(version, stations); } return "".equals(message) ? null : message; }
From source file:com.basetechnology.s0.agentserver.script.runtime.ExceptionInfo.java
public static ExceptionInfo fromJson(JSONObject exceptionJson) throws ParseException, AgentServerException { String type = exceptionJson.optString("type"); long time = DateUtils.parseRfcString(exceptionJson.optString("time")); String message = exceptionJson.optString("message"); String scriptName = exceptionJson.optString("script"); // Validate keys JsonUtils.validateKeys(exceptionJson, "ExceptionInfo", new ArrayList<String>(Arrays.asList("type", "time", "message", "script"))); // Generate and return an ExceptionInfo object return new ExceptionInfo(null, type, message, time, scriptName); }
From source file:com.sina.weibo.sdk_lib.openapi.models.Comment.java
public static Comment parse(JSONObject jsonObject) { if (null == jsonObject) { return null; }//from w ww. j a va2 s.co m Comment comment = new Comment(); comment.created_at = jsonObject.optString("created_at"); comment.id = jsonObject.optString("id"); comment.text = jsonObject.optString("text"); comment.source = jsonObject.optString("source"); comment.user = User.parse(jsonObject.optJSONObject("user")); comment.mid = jsonObject.optString("mid"); comment.idstr = jsonObject.optString("idstr"); comment.status = Status.parse(jsonObject.optJSONObject("status")); comment.reply_comment = Comment.parse(jsonObject.optJSONObject("reply_comment")); return comment; }
From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.AppObj.java
public static Intent getLaunchIntent(Context context, DbObj obj) { JSONObject content = obj.getJson(); if (content.has(ANDROID_PACKAGE_NAME)) { Uri appFeed = obj.getContainingFeed().getUri(); String action = content.optString(ANDROID_ACTION); String pkgName = content.optString(ANDROID_PACKAGE_NAME); String className = content.optString(ANDROID_CLASS_NAME); Intent launch = new Intent(action); launch.setClassName(pkgName, className); launch.addCategory(Intent.CATEGORY_LAUNCHER); // TODO: feed for related objs, not parent feed launch.putExtra(AppState.EXTRA_FEED_URI, appFeed); launch.putExtra(AppState.EXTRA_OBJ_HASH, obj.getHash()); // TODO: Remove launch.putExtra("obj", content.toString()); List<ResolveInfo> resolved = context.getPackageManager().queryIntentActivities(launch, 0); if (resolved.size() > 0) { return launch; }//from ww w .ja va 2 s . co m Intent market = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + pkgName)); return market; } else if (content.has(WEB_URL)) { Intent app = new Intent(Intent.ACTION_VIEW, Uri.parse(content.optString(WEB_URL))); app.setClass(context, AppFinderActivity.class); app.putExtra(Musubi.EXTRA_FEED_URI, Feed.uriForName(obj.getFeedName())); return app; } return null; }
From source file:com.citrus.sdk.payment.PaymentBill.java
public static PaymentBill fromJSON(String json) { PaymentBill paymentBill = null;/*from www . j a v a 2 s. co m*/ JSONObject billObject = null; try { billObject = new JSONObject(json); } catch (JSONException e) { e.printStackTrace(); } if (billObject != null) { Amount amount = null; String requestSignature = null; String merchantTransactionId = null; // TODO: Do the validation of the transaction id length String merchantAccessKey = null; String returnUrl = null; String notifyUrl = null; Map<String, String> customParametersMap = null; amount = Amount.fromJSONObject(billObject.optJSONObject("amount")); requestSignature = billObject.optString("requestSignature"); merchantTransactionId = billObject.optString("merchantTxnId"); merchantAccessKey = billObject.optString("merchantAccessKey"); returnUrl = billObject.optString("returnUrl"); notifyUrl = billObject.optString("notifyUrl"); JSONObject customParamsObject = billObject.optJSONObject("customParameters"); if (customParamsObject != null) { customParametersMap = new HashMap<>(); Iterator<String> iter = customParamsObject.keys(); while (iter.hasNext()) { String key = iter.next(); String value = customParamsObject.optString(key); customParametersMap.put(key, value); } } if (amount != null && requestSignature != null && returnUrl != null && merchantAccessKey != null && merchantTransactionId != null) { paymentBill = new PaymentBill(amount, requestSignature, merchantTransactionId, merchantAccessKey, returnUrl, notifyUrl, customParametersMap); } } return paymentBill; }