List of usage examples for org.json JSONObject optString
public String optString(String key)
From source file:com.citrus.sdk.CitrusActivity.java
private void processresponse(String response, String error) { TransactionResponse transactionResponse = null; if (!android.text.TextUtils.isEmpty(response)) { try {/*from w w w .ja va2s. c om*/ JSONObject redirect = new JSONObject(response); mpiServletUrl = redirect.optString("redirectUrl"); if (!android.text.TextUtils.isEmpty(mpiServletUrl)) { mPaymentWebview.loadUrl(mpiServletUrl); if (mPaymentOption != null) { EventsManager.logWebViewEvents(CitrusActivity.this, WebViewEvents.OPEN, mPaymentOption.getAnalyticsPaymentType()); //analytics event - WebView Event } } else { transactionResponse = new TransactionResponse(TransactionResponse.TransactionStatus.FAILED, response, mTransactionId); sendResult(transactionResponse); } } catch (JSONException e) { e.printStackTrace(); } } else { transactionResponse = new TransactionResponse(TransactionResponse.TransactionStatus.FAILED, error, mTransactionId); sendResult(transactionResponse); } }
From source file:com.quantcast.measurement.service.QCLocation.java
private MeasurementLocation parseJson(String jsonString) throws JSONException { JSONObject json = new JSONObject(jsonString); if (OK.equals(json.optString(STATUS))) { JSONArray resultsArray = json.optJSONArray(RESULTS); if (resultsArray != null) { JSONArray addressComponents; for (int i = 0; i < resultsArray.length(); i++) { addressComponents = resultsArray.getJSONObject(i).optJSONArray(ADDRESS); if (addressComponents != null) { String country = "", locality = "", state = "", postalCode = ""; for (int j = 0; j < addressComponents.length(); j++) { JSONObject obj = addressComponents.getJSONObject(j); JSONArray types = obj.optJSONArray(TYPES); if (types != null) { if (containsString(types, LOCALITY)) locality = obj.getString(SHORT_NAME); if (containsString(types, STATE)) state = obj.getString(SHORT_NAME); if (containsString(types, COUNTRY)) country = obj.getString(SHORT_NAME); if (containsString(types, POSTAL_CODE)) postalCode = obj.getString(SHORT_NAME); }//ww w .j av a 2 s .c om } return new MeasurementLocation(country, state, locality, postalCode); } } } } return null; }
From source file:com.kimkha.finanvita.billing.SkuDetails.java
public SkuDetails(String itemType, String jsonSkuDetails) throws JSONException { mItemType = itemType;//from w w w. j ava 2 s . co m mJson = jsonSkuDetails; JSONObject o = new JSONObject(mJson); mSku = o.optString("productId"); mType = o.optString("type"); mPrice = o.optString("price"); mPriceAmount = o.optDouble("price_amount_micros") / 1000000; mTitle = o.optString("title"); mDescription = o.optString("description"); mCurrency = o.optString("price_currency_code"); }
From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.ProfileObj.java
public void handleDirectMessage(Context context, Contact from, JSONObject obj) { String name = obj.optString(NAME); String id = Long.toString(from.id); ContentValues values = new ContentValues(); values.put(Contact.NAME, name);// w w w .j a v a2 s .c o m context.getContentResolver().update(Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/contacts"), values, "_id=?", new String[] { id }); }
From source file:com.harmazing.aixiumama.model.sina.models.Geo.java
public static Geo parse(JSONObject jsonObject) { if (null == jsonObject) { return null; }/*from w w w . j a va 2 s.c o m*/ Geo geo = new Geo(); geo.longitude = jsonObject.optString("longitude"); geo.latitude = jsonObject.optString("latitude"); geo.city = jsonObject.optString("city"); geo.province = jsonObject.optString("province"); geo.city_name = jsonObject.optString("city_name"); geo.province_name = jsonObject.optString("province_name"); geo.address = jsonObject.optString("address"); geo.pinyin = jsonObject.optString("pinyin"); geo.more = jsonObject.optString("more"); return geo; }
From source file:com.mifos.mifosxdroid.dialogfragments.loanchargedialog.LoanChargeDialogFragment.java
@Override public void showAllChargesV3(ResponseBody result) { /* Activity is null - Fragment has been detached; no need to do anything. */ if (getActivity() == null) return;/*www . ja va 2 s . c o m*/ Log.d(LOG_TAG, ""); final List<Charges> charges = new ArrayList<>(); // you can use this array to populate your spinner final ArrayList<String> chargesNames = new ArrayList<String>(); //Try to get response body BufferedReader reader = null; StringBuilder sb = new StringBuilder(); try { reader = new BufferedReader(new InputStreamReader(result.byteStream())); String line; while ((line = reader.readLine()) != null) { sb.append(line); } JSONObject obj = new JSONObject(sb.toString()); if (obj.has("chargeOptions")) { JSONArray chargesTypes = obj.getJSONArray("chargeOptions"); for (int i = 0; i < chargesTypes.length(); i++) { JSONObject chargesObject = chargesTypes.getJSONObject(i); Charges charge = new Charges(); charge.setId(chargesObject.optInt("id")); charge.setName(chargesObject.optString("name")); charges.add(charge); chargesNames.add(chargesObject.optString("name")); chargeNameIdHashMap.put(charge.getName(), charge.getId()); } } String stringResult = sb.toString(); } catch (Exception e) { Log.e(LOG_TAG, "", e); } final ArrayAdapter<String> chargesAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, chargesNames); chargesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sp_charge_name.setAdapter(chargesAdapter); sp_charge_name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { Id = chargeNameIdHashMap.get(chargesNames.get(i)); Log.d("chargesoptionss" + chargesNames.get(i), String.valueOf(Id)); if (Id != -1) { } else { Toast.makeText(getActivity(), getString(R.string.error_select_charge), Toast.LENGTH_SHORT) .show(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); }
From source file:com.vk.sdkweb.api.model.VKApiSchool.java
/** * Fills a School instance from JSONObject. *//* www . j av a 2s . c om*/ public VKApiSchool parse(JSONObject from) { id = from.optInt("id"); country_id = from.optInt("country_id"); city_id = from.optInt("city_id"); name = from.optString("name"); year_from = from.optInt("year_from"); year_to = from.optInt("year_to"); year_graduated = from.optInt("year_graduated"); clazz = from.optString("class"); speciality = from.optString("speciality"); return this; }
From source file:edu.stanford.mobisocial.dungbeetle.ImageViewerActivity.java
@Override public void onResume() { super.onResume(); if (mIntent.hasExtra("image_url")) { String url = mIntent.getStringExtra("image_url"); ((App) getApplication()).objectImages.lazyLoadImage(url.hashCode(), Uri.parse(url), im); bitmap = mgr.getBitmap(url.hashCode(), url); } else if (mIntent.hasExtra("b64Bytes")) { String b64Bytes = mIntent.getStringExtra("b64Bytes"); ((App) getApplication()).objectImages.lazyLoadImage(b64Bytes.hashCode(), b64Bytes, im); bitmap = mgr.getBitmapB64(b64Bytes.hashCode(), b64Bytes); } else if (mIntent.hasExtra("bytes")) { byte[] bytes = mIntent.getByteArrayExtra("bytes"); ((App) getApplication()).objectImages.lazyLoadImage(bytes.hashCode(), bytes, im); bitmap = mgr.getBitmap(bytes.hashCode(), bytes); } else if (mIntent.hasExtra("obj")) { try {//from w w w. j av a2 s .c om final JSONObject content = new JSONObject(mIntent.getStringExtra("obj")); byte[] bytes = FastBase64.decode(content.optString(PictureObj.DATA)); ((App) getApplication()).objectImages.lazyLoadImage(bytes.hashCode(), bytes, im); bitmap = mgr.getBitmap(bytes.hashCode(), bytes); } catch (JSONException e) { } } if (mIntent.hasExtra("objHash")) { if (!ContentCorral.CONTENT_CORRAL_ENABLED) { return; } long objHash = mIntent.getLongExtra("objHash", -1); final DbObj obj = App.instance().getMusubi().objForHash(objHash); final JSONObject json = obj.getJson(); if (json.has(CorralClient.OBJ_LOCAL_URI)) { // TODO: this is a proof-of-concept. new Thread() { public void run() { try { if (!mCorralClient.fileAvailableLocally(obj)) { //toast("Trying to go HD..."); } // Log.d(TAG, "Trying to go HD..."); final Uri fileUri = mCorralClient.fetchContent(obj); if (fileUri == null) { try { Log.d(TAG, "Failed to go HD for " + json.getString(CorralClient.OBJ_LOCAL_URI)); } catch (JSONException e) { Log.d(TAG, "Failed to go HD for " + json); } return; } // Log.d(TAG, "Opening HD file " + fileUri); InputStream is = getContentResolver().openInputStream(fileUri); BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; Matrix matrix = new Matrix(); float rotation = PhotoTaker.rotationForImage(ImageViewerActivity.this, fileUri); if (rotation != 0f) { matrix.preRotate(rotation); } bitmap = BitmapFactory.decodeStream(is, null, options); int width = bitmap.getWidth(); int height = bitmap.getHeight(); bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); runOnUiThread(new Runnable() { @Override public void run() { im.setImageBitmap(bitmap); } }); } catch (IOException e) { // toast("Failed to go HD"); Log.e(TAG, "Failed to get hd content", e); // continue } }; }.start(); } } }
From source file:io.mapsquare.osmcontributor.utils.ways.Geocoder.java
public String reverseGeocoding(double lat, double lng) { String url = String.format(URL, lat, lng); Request request = new Request.Builder().url(url).build(); try {//ww w . j ava 2 s .c o m Response response = client.newCall(request).execute(); String responseBody = response.body().string(); JSONObject reader = new JSONObject(responseBody); return reader.optString("display_name"); } catch (IOException | JSONException e) { Timber.e(e, "Failed to parse response"); } return ""; }
From source file:uk.ac.imperial.presage2.core.cli.run.ExecutorModule.java
/** * <p>/* w w w . j a va 2 s. c o m*/ * Load an {@link AbstractModule} which can inject an * {@link ExecutorManager} with the appropriate {@link SimulationExecutor}s * as per provided configuration. * </p> * * <p> * The executor config can be provided in two ways (in order of precedence): * </p> * <ul> * <li><code>executors.properties</code> file on the classpath. This file * should contain a <code>module</code> key who's value is the fully * qualified name of a class which extends {@link AbstractModule} and has a * public constructor which takes a single {@link Properties} object as an * argument or public no-args constructor. An instance of this class will be * returned.</li> * <li><code>executors.json</code> file on the classpath. This file contains * a specification of the executors to load in JSON format. If this file is * valid we will instantiate each executor defined in the spec and add it to * an {@link ExecutorModule} which will provide the bindings for them.</li> * </ul> * * <h3>executors.json format</h3> * * <p> * The <code>executors.json</code> file should contain a JSON object with * the following: * <ul> * <li><code>executors</code> key whose value is an array. Each element of * the array is a JSON object with the following keys: * <ul> * <li><code>class</code>: the fully qualified name of the executor class.</li> * <li><code>args</code>: an array of arguments to pass to a public * constructor of the class.</li> * <li><code>enableLogs</code> (optional): boolean value whether this * executor should save logs to file. Defaults to global value.</li> * <li><code>logDir</code> (optional): string path to save logs to. Defaults * to global value</li> * </ul> * </li> * <li><code>enableLogs</code> (optional): Global value for enableLogs for * each executor. Defaults to false.</li> * <li><code>logDir</code> (optional): Global value for logDir for each * executor. Default values depend on the executor.</li> * </ul> * </p> * <p> * e.g.: * </p> * * <pre class="prettyprint"> * { * "executors": [{ * "class": "my.fully.qualified.Executor", * "args": [1, "some string", true] * },{ * ... * }], * "enableLogs": true * } * </pre> * * @return */ public static AbstractModule load() { Logger logger = Logger.getLogger(ExecutorModule.class); // look for executors.properties // This defines an AbstractModule to use instead of this one. // We try and load the module class given and return it. try { Properties execProps = new Properties(); execProps.load(ExecutorModule.class.getClassLoader().getResourceAsStream("executors.properties")); String moduleName = execProps.getProperty("module", ""); Class<? extends AbstractModule> module = Class.forName(moduleName).asSubclass(AbstractModule.class); // look for suitable ctor, either Properties parameter or default Constructor<? extends AbstractModule> ctor; try { ctor = module.getConstructor(Properties.class); return ctor.newInstance(execProps); } catch (NoSuchMethodException e) { ctor = module.getConstructor(); return ctor.newInstance(); } } catch (Exception e) { logger.debug("Could not create module from executors.properties"); } // executors.properties fail, look for executors.json // This file defines a set of classes to load with parameters for the // constructor. // We try to create each defined executor and add it to this // ExecutorModule. try { // get executors.json file and parse to JSON. // throws NullPointerException if file doesn't exist, or // JSONException if we can't parse the JSON. InputStream is = ExecutorModule.class.getClassLoader().getResourceAsStream("executors.json"); logger.debug("Processing executors from executors.json"); JSONObject execConf = new JSONObject(new JSONTokener(new InputStreamReader(is))); // Create our module and look for executor specs under the executors // array in the JSON. ExecutorModule module = new ExecutorModule(); JSONArray executors = execConf.getJSONArray("executors"); // optional global settings boolean enableLogs = execConf.optBoolean("enableLogs", false); String logDir = execConf.optString("logDir"); logger.info("Building Executors from executors.json"); // Try and instantiate an instance of each executor in the spec. for (int i = 0; i < executors.length(); i++) { try { JSONObject executorSpec = executors.getJSONObject(i); String executorClass = executorSpec.getString("class"); JSONArray args = executorSpec.getJSONArray("args"); Class<? extends SimulationExecutor> clazz = Class.forName(executorClass) .asSubclass(SimulationExecutor.class); // build constructor args. // We assume all types are in primitive form where // applicable. // The only available types are boolean, int, double and // String. Class<?>[] argTypes = new Class<?>[args.length()]; Object[] argValues = new Object[args.length()]; for (int j = 0; j < args.length(); j++) { argValues[j] = args.get(j); Class<?> type = argValues[j].getClass(); if (type == Boolean.class) type = Boolean.TYPE; else if (type == Integer.class) type = Integer.TYPE; else if (type == Double.class) type = Double.TYPE; argTypes[j] = type; } SimulationExecutor exe = clazz.getConstructor(argTypes).newInstance(argValues); logger.debug("Adding executor to pool: " + exe.toString()); module.addExecutorInstance(exe); // logging config boolean exeEnableLog = executorSpec.optBoolean("enableLogs", enableLogs); String exeLogDir = executorSpec.optString("logDir", logDir); exe.enableLogs(exeEnableLog); if (exeLogDir.length() > 0) { exe.setLogsDirectory(exeLogDir); } } catch (JSONException e) { logger.warn("Error parsing executor config", e); } catch (ClassNotFoundException e) { logger.warn("Unknown executor class in config", e); } catch (IllegalArgumentException e) { logger.warn("Illegal arguments for executor ctor", e); } catch (NoSuchMethodException e) { logger.warn("No matching public ctor for args in executor config", e); } catch (Exception e) { logger.warn("Could not create executor from specification", e); } } return module; } catch (JSONException e) { logger.debug("Could not create module from executors.json"); } catch (NullPointerException e) { logger.debug("Could not open executors.json"); } // no executor config, use a default config: 1 local sub process // executor. logger.info("Using default ExecutorModule."); return new ExecutorModule(1); }