List of usage examples for org.json JSONObject getDouble
public double getDouble(String key) throws JSONException
From source file:net.phase.wallet.Currency.java
private void updateBalanceFromUrl(String url) throws IOException, JSONException, java.text.ParseException { if (url.equals(emptyBaseUrl)) { Log.i("balance", "skipping URL " + url); return;//from www. java 2 s. c om } Log.i("balance", "fetching URL " + url); HttpClient client = new DefaultHttpClient(); HttpGet hg = new HttpGet(url); HttpResponse response = client.execute(hg); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { JSONObject resp = new JSONObject(EntityUtils.toString(response.getEntity())); // JSONObject.keys() returns Iterator<String> but for some reason // isn't typed that way @SuppressWarnings("unchecked") Iterator<String> itr = resp.keys(); // look through every transaction while (itr.hasNext()) { JSONObject txObject = resp.getJSONObject(itr.next()); String txHash = txObject.getString("hash"); String inKeyHash = "unknown"; // only process transaction if we haven't seen it before if (!transactionCache.contains(txHash)) { Log.i("balance", "Parsing txObject " + txHash); transactionCache.add(txHash); // find the in transaction JSONArray txsIn = txObject.getJSONArray("in"); Date date = formatter.parse(txObject.getString("time")); for (int i = 0; i < txsIn.length(); i++) { JSONObject inRecord = txsIn.getJSONObject(i); try { inKeyHash = inRecord.optString("address"); // if one of our keys is there, we are paying :( if (Key.arrayContains(wallet.keys, inKeyHash)) { JSONObject prevRecord = inRecord.getJSONObject("prev_out"); // if we paid for part of this transaction, // record this. pendingDebits.add(new prevout(txHash, prevRecord.getString("hash"), prevRecord.getInt("n"), date, inKeyHash)); } } catch (JSONException e) { // no address. Probably a generation transaction } } // find the out transaction JSONArray txsOut = txObject.getJSONArray("out"); for (int i = 0; i < txsOut.length(); i++) { JSONObject outRecord = txsOut.getJSONObject(i); String outKeyHash = outRecord.optString("address"); // convert to microbitcoins for accuracy long value = (long) (outRecord.getDouble("value") * SATOSHIS_PER_BITCOIN); // store the out transaction, this is used later on txs.add(new tx(txHash, i, value, outKeyHash, inKeyHash)); // if one of our keys is there, add the balance if (Key.arrayContains(wallet.keys, outKeyHash)) { transactions.add(new Transaction(date, value, inKeyHash, outKeyHash)); balance += value; } } } } } else { Log.e("wallet", "Got " + response.getStatusLine().getStatusCode() + " back from HTTP GET"); } }
From source file:fr.qinder.tools.JSON.java
/** * Get value of the key from a JSONObject. If the key not exists in the * JSONObject, defValue is return.//from ww w . j a v a 2s . c o m * * @param obj * JSONObject for getting the value * @param key * String of the key * @param defValue * Default value if key not exists * @return The value if key exist, defValue else */ @SuppressWarnings("unchecked") private static <T> T getValue(JSONObject obj, String key, T defValue) throws JSONException { T res = defValue; if (defValue instanceof Double) { res = (T) ((Double) obj.getDouble(key)); } else if (defValue instanceof Integer) { res = (T) ((Integer) obj.getInt(key)); } else if (defValue instanceof Boolean) { res = (T) ((Boolean) obj.getBoolean(key)); } else if (defValue instanceof Long) { res = (T) ((Long) obj.getLong(key)); } else if (defValue instanceof String) { res = (T) obj.getString(key); } else if (defValue instanceof JSONObject) { res = (T) obj.getJSONObject(key); } else if (defValue instanceof JSONArray) { res = (T) obj.getJSONArray(key); } return res; }
From source file:com.graphhopper.http.GraphHopperWeb.java
@Override public GHResponse route(GHRequest request) { StopWatch sw = new StopWatch().start(); double took = 0; try {/* w w w . java2 s . c o m*/ String places = ""; for (GHPoint p : request.getPoints()) { places += "point=" + p.lat + "," + p.lon + "&"; } String url = serviceUrl + "?" + places + "&type=json" + "&points_encoded=" + pointsEncoded + "&min_path_precision=" + request.getHint("douglas.minprecision", 1) + "&algo=" + request.getAlgorithm() + "&locale=" + request.getLocale().toString() + "&elevation=" + withElevation; if (!request.getVehicle().isEmpty()) url += "&vehicle=" + request.getVehicle(); if (!key.isEmpty()) url += "&key=" + key; String str = downloader.downloadAsString(url); JSONObject json = new JSONObject(str); GHResponse res = new GHResponse(); if (json.getJSONObject("info").has("errors")) { JSONArray errors = json.getJSONObject("info").getJSONArray("errors"); for (int i = 0; i < errors.length(); i++) { JSONObject error = errors.getJSONObject(i); String exClass = error.getString("details"); String exMessage = error.getString("message"); if (exClass.equals(UnsupportedOperationException.class.getName())) { res.addError(new UnsupportedOperationException(exMessage)); } else if (exClass.equals(IllegalStateException.class.getName())) { res.addError(new IllegalStateException(exMessage)); } else if (exClass.equals(RuntimeException.class.getName())) { res.addError(new RuntimeException(exMessage)); } else if (exClass.equals(IllegalArgumentException.class.getName())) { res.addError(new IllegalArgumentException(exMessage)); } else { res.addError(new Exception(exClass + " " + exMessage)); } } return res; } else { took = json.getJSONObject("info").getDouble("took"); JSONArray paths = json.getJSONArray("paths"); JSONObject firstPath = paths.getJSONObject(0); double distance = firstPath.getDouble("distance"); int time = firstPath.getInt("time"); PointList pointList; if (pointsEncoded) { String pointStr = firstPath.getString("points"); pointList = WebHelper.decodePolyline(pointStr, 100, withElevation); } else { JSONArray coords = firstPath.getJSONObject("points").getJSONArray("coordinates"); pointList = new PointList(coords.length(), withElevation); for (int i = 0; i < coords.length(); i++) { JSONArray arr = coords.getJSONArray(i); double lon = arr.getDouble(0); double lat = arr.getDouble(1); if (withElevation) pointList.add(lat, lon, arr.getDouble(2)); else pointList.add(lat, lon); } } if (instructions) { JSONArray instrArr = firstPath.getJSONArray("instructions"); InstructionList il = new InstructionList(trMap.getWithFallBack(request.getLocale())); for (int instrIndex = 0; instrIndex < instrArr.length(); instrIndex++) { JSONObject jsonObj = instrArr.getJSONObject(instrIndex); double instDist = jsonObj.getDouble("distance"); String text = jsonObj.getString("text"); long instTime = jsonObj.getLong("time"); int sign = jsonObj.getInt("sign"); JSONArray iv = jsonObj.getJSONArray("interval"); int from = iv.getInt(0); int to = iv.getInt(1); PointList instPL = new PointList(to - from, withElevation); for (int j = from; j <= to; j++) { instPL.add(pointList, j); } // TODO way and payment type Instruction instr = new Instruction(sign, text, InstructionAnnotation.EMPTY, instPL) .setDistance(instDist).setTime(instTime); il.add(instr); } res.setInstructions(il); } return res.setPoints(pointList).setDistance(distance).setMillis(time); } } catch (Exception ex) { throw new RuntimeException( "Problem while fetching path " + request.getPoints() + ": " + ex.getMessage(), ex); } finally { logger.debug("Full request took:" + sw.stop().getSeconds() + ", API took:" + took); } }
From source file:com.jennifer.ui.chart.grid.RadarGrid.java
public void drawCustom(Transform root) { this.root = root; double width = chart.area("width"), height = chart.area("height"); double startY = -w; double startX = 0; JSONArray position = new JSONArray(); for (int i = 0; i < count; i++) { double x2 = centerX + startX, y2 = centerY + startY; root.line(new JSONObject().put("x1", centerX).put("y1", centerY).put("x2", x2).put("y2", y2) .put("stroke", chart.theme("gridAxisBorderColor")) .put("stroke-width", chart.theme("gridBorderWidth"))); position.put(new JSONObject().put("x1", centerX).put("y1", centerY).put("x2", x2).put("y2", y2)); double ty = y2, tx = x2; String talign = "middle"; if (y2 > centerY) { ty = y2 + 20;//from ww w. j a v a 2s . com } else if (y2 < centerY) { ty = y2 - 10; } if (x2 > centerX + 10) { talign = "start"; tx += 10; } else if (x2 < centerX - 10) { talign = "end"; tx -= 10; } else { talign = "middle"; } if (!hideText) { root.text(new JSONObject().put("x", tx).put("y", ty).put("text-anchor", talign).put("fill", chart.theme("gridFontColor"))).textNode(domain.getString(i)); } JSONObject obj = MathUtil.rotate(startX, startY, unit); startX = obj.getDouble("x"); startY = obj.getDouble("y"); } if (line) { // area split line startY = -w; double stepBase = 0; for (int i = 0; i < step; i++) { if (i == 0 && extra) { startY += h; continue; } if (shape == "circle") { drawCircle(centerX, centerY, 0, startY, count); } else { drawRadial(centerX, centerY, 0, startY, count, unit); } if (!hideText) { root.text(new JSONObject().put("x", centerX).put("y", centerY + (startY + 5)) .put("font-size", 12).put("fill", chart.theme("gridFontColor"))) .textNode(getFormatString(max - stepBase)); } startY += h; stepBase += stepValue; } } }
From source file:com.jennifer.ui.chart.grid.RadarGrid.java
private void drawRadial(double centerX, double centerY, double x, double y, int count, double unit) { Transform group = root.group(); JSONArray points = new JSONArray(); points.put(new JSONArray().put(centerX + x).put(centerY + y)); double startX = x; double startY = y; for (int i = 0; i < count; i++) { JSONObject obj = MathUtil.rotate(startX, startY, unit); startX = obj.getDouble("x"); startY = obj.getDouble("y"); points.put(new JSONArray().put(centerX + startX).put(centerY + startY)); }/* w w w. j av a2 s. co m*/ Path path = group .path(new JSONObject().put("fill", "none").put("stroke", chart.theme("gridAxisBorderColor")) .put("stroke-width", chart.theme("gridBorderWidth"))); for (int i = 0, len = points.length(); i < len; i++) { JSONArray point = (JSONArray) points.getJSONArray(i); if (i == 0) { path.MoveTo(point.getDouble(0), point.getDouble(1)); } else { path.LineTo(point.getDouble(0), point.getDouble(1)); } } path.LineTo(points.getJSONArray(0).getDouble(0), points.getJSONArray(0).getDouble(1)); }
From source file:com.jennifer.ui.chart.grid.RadarGrid.java
public JSONObject get(int index, double value) { double rate = value / max; double height = Math.abs(w); double pos = height * rate; double y = -pos, x = 0; JSONObject o = MathUtil.rotate(x, y, unit * index); return new JSONObject().put("x", height + o.getDouble("x")).put("y", height + o.getDouble("y")); }
From source file:net.openwatch.acluaz.fragment.FormFragment.java
/** * maps json fields to orm object fields * @param json//from www.j av a 2s . c om */ private static int jsonToDatabase(Context c, JSONObject json, int existing_db_id) { String TAG = "FormFragment-jsonToDatabase"; Incident incident = null; if (existing_db_id == -1) { incident = new Incident(); incident.uuid.set(Constants.generateUUID()); } else incident = Incident.objects(c).get(existing_db_id); try { JSONObject user_json; if (json.has(c.getString(R.string.user_tag))) { user_json = json.getJSONObject(c.getString(R.string.user_tag)); if (user_json.has(c.getString(R.string.first_name_tag))) incident.first_name.set(user_json.getString(c.getString(R.string.first_name_tag))); if (user_json.has(c.getString(R.string.last_name_tag))) incident.last_name.set(user_json.getString(c.getString(R.string.last_name_tag))); if (user_json.has(c.getString(R.string.address1_tag))) incident.address_1.set(user_json.getString(c.getString(R.string.address1_tag))); if (user_json.has(c.getString(R.string.address2_tag))) incident.address_2.set(user_json.getString(c.getString(R.string.address2_tag))); if (user_json.has(c.getString(R.string.city_tag))) incident.city.set(user_json.getString(c.getString(R.string.city_tag))); if (user_json.has(c.getString(R.string.state_tag))) incident.state.set(user_json.getString(c.getString(R.string.state_tag))); if (user_json.has(c.getString(R.string.zipcode_tag))) incident.zip.set(user_json.getInt(c.getString(R.string.zipcode_tag))); if (user_json.has(c.getString(R.string.phone_tag))) incident.phone.set(user_json.getString(c.getString(R.string.phone_tag))); if (user_json.has(c.getString(R.string.email_tag))) incident.email.set(user_json.getString(c.getString(R.string.email_tag))); } else { Log.e(TAG, "no user object present"); } JSONObject report_json; if (json.has(c.getString(R.string.report_tag))) { report_json = json.getJSONObject(c.getString(R.string.report_tag)); if (report_json.has(c.getString(R.string.agency_tag))) incident.agency.set(report_json.getString(c.getString(R.string.agency_tag))); if (report_json.has(c.getString(R.string.location_tag))) incident.location.set(report_json.getString(c.getString(R.string.location_tag))); if (report_json.has(c.getString(R.string.date_tag))) incident.date.set(report_json.getString(c.getString(R.string.date_tag))); if (report_json.has(c.getString(R.string.narrative_tag))) incident.description.set(report_json.getString(c.getString(R.string.narrative_tag))); if (report_json.has(c.getString(R.string.device_location_tag))) { incident.device_lat.set(report_json.getDouble(c.getString(R.string.device_lat))); incident.device_lon.set(report_json.getDouble(c.getString(R.string.device_lon))); } } else { Log.e(TAG, "no report object present"); } incident.save(c); return incident.getId(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return -1; }
From source file:com.mygdx.game.multiplayer.MultiplayerGameScreen.java
@Override public void onGameUpdateReceived(String message) { try {//from ww w .ja v a 2 s . com JSONObject data = new JSONObject(message); float x = (float) data.getDouble("x"); float y = (float) data.getDouble("y"); float width = (float) data.getDouble("width"); float height = (float) data.getDouble("height"); renderer.updateEnemyLocation(x, y, width, height); } catch (Exception e) { // exception in onMoveNotificationReceived } }
From source file:com.funzio.pure2D.particles.nova.vo.NovaVO.java
protected static ArrayList<Float> getListFloat(final JSONObject json, final String field) throws JSONException { // field check if (!json.has(field)) { return null; }/*from www.j a v a 2 s. c o m*/ final ArrayList<Float> result = new ArrayList<Float>(); try { final JSONArray array = json.getJSONArray(field); if (array != null) { final int size = array.length(); for (int i = 0; i < size; i++) { result.add((float) array.getDouble(i)); } } } catch (JSONException e) { // single value result.add((float) json.getDouble(field)); } return result; }
From source file:org.boris.xlloop.http.JSONCodec.java
private static XLoper decode(JSONObject jo) throws JSONException { switch (jo.getInt("type")) { case XLoper.xlTypeBool: return jo.getBoolean("bool") ? XLBool.TRUE : XLBool.FALSE; case XLoper.xlTypeErr: return new XLError(jo.getInt("error")); case XLoper.xlTypeInt: return new XLInt(jo.getInt("int")); case XLoper.xlTypeMissing: return XLMissing.MISSING; case XLoper.xlTypeMulti: int rows = jo.getInt("rows"); int cols = jo.getInt("cols"); int len = rows * cols; XLoper[] a = new XLoper[len]; JSONArray ja = jo.getJSONArray("array"); for (int i = 0; i < len; i++) { a[i] = decode(ja.getJSONObject(i)); }//from w w w. j av a 2s .c o m return new XLArray(a, rows, cols); case XLoper.xlTypeNil: return XLNil.NIL; case XLoper.xlTypeNum: return new XLNum(jo.getDouble("num")); case XLoper.xlTypeStr: return new XLString(jo.getString("str")); case XLoper.xlTypeSRef: return new XLSRef(jo.getInt("colFirst"), jo.getInt("colLast"), jo.getInt("rowFirst"), jo.getInt("rowLast")); } return null; }