List of usage examples for org.json JSONObject getDouble
public double getDouble(String key) throws JSONException
From source file:com.poguico.palmabici.parsers.Parser.java
public static ArrayList<Station> parseNetworkJSON(String data) { ArrayList<Station> stations = new ArrayList<Station>(); JSONArray jsonArray;/*from ww w . ja va2 s. c o m*/ JSONObject jsonObject; Long lngAcum = 0L, latAcum = 0L; int id; try { jsonArray = new JSONArray(data); for (int i = 0; i < jsonArray.length(); i++) { jsonObject = jsonArray.getJSONObject(i); lngAcum += jsonObject.getLong("lng"); latAcum += jsonObject.getLong("lat"); id = jsonObject.getInt("id"); stations.add(new Station(id, jsonObject.getString("name"), jsonObject.getDouble("lng") / 1e6, jsonObject.getDouble("lat") / 1e6, jsonObject.getInt("free"), jsonObject.getInt("bikes"), false, NetworkStationAlarm.hasAlarm(id))); } } catch (Exception e) { e.printStackTrace(); } return stations; }
From source file:org.melato.bus.otp.OTPParser.java
static Leg parseLeg(JSONObject json) throws JSONException { String mode = json.getString("mode"); Leg leg = null;// w w w. j av a2s .com if ("WALK".equals(mode)) { WalkLeg walk = new WalkLeg(); leg = walk; } else if ("TRANSFER".equals(mode)) { TransferLeg transfer = new TransferLeg(); transfer.from = getStop(json, "from"); transfer.to = getStop(json, "to"); leg = transfer; } else { TransitLeg transit = new TransitLeg(); transit.routeId = json.getString("routeId"); transit.label = json.getString("routeShortName"); transit.from = getStop(json, "from"); transit.to = getStop(json, "to"); leg = transit; } leg.distance = (float) json.getDouble("distance"); leg.duration = (int) (json.getLong("duration") / 1000L); leg.startTime = new Date(json.getLong("startTime")); leg.endTime = new Date(json.getLong("endTime")); leg.mode = mode; return leg; }
From source file:com.morpho.android.data.GeoPoint.java
/** {@inheritDoc} */ @Override/*from ww w. j av a2s . c o m*/ public void fromJSON(String json) { try { JSONObject src = new JSONObject(json); latitude = src.isNull("latitude") ? null : src.getDouble("latitude"); longitude = src.isNull("longitude") ? null : src.getDouble("longitude"); } catch (JSONException ex) { throw new RuntimeException(ex); } }
From source file:com.chainsaw.clearweather.BackgroundFetch.java
@Override protected WeatherData doInBackground(String... params) { publishProgress(10);//from w ww. j a v a 2s . c o m HttpURLConnection con = null; InputStream is = null; if (!isNetworkAvailable()) { fetchStatus = NO_NETWORK; } if (isNetworkAvailable()) { try { con = (HttpURLConnection) (new URL(params[0])).openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); con.setDoOutput(true); con.setConnectTimeout(SERVER_TIMEOUT); con.connect(); buffer = new StringBuffer(); is = con.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line = null; while ((line = br.readLine()) != null) buffer.append(line); is.close(); con.disconnect(); } catch (Throwable t) { fetchStatus = SERVER_ERROR; t.printStackTrace(); } finally { try { is.close(); } catch (Throwable t) { fetchStatus = SERVER_ERROR; t.printStackTrace(); } try { con.disconnect(); } catch (Throwable t) { fetchStatus = SERVER_ERROR; t.printStackTrace(); } } try { weatherData = (buffer.toString() == null) ? new JSONObject() : new JSONObject(buffer.toString()); fetchStatus = DONE; } catch (Throwable e) { fetchStatus = NO_DATA; e.printStackTrace(); } is = null; con = null; try { if ((fetchStatus == DONE) && (weatherData != null)) { WeatherData.newDataStatus = DONE; JSONObject mainObj = weatherData.getJSONObject("main"); JSONArray weatherObj = weatherData.getJSONArray("weather"); returnData = new WeatherData(true, (int) (Math.round(mainObj.getDouble("temp") - 273.15)), ((int) (Math.round(mainObj.getInt("humidity")))), weatherData.getString("name"), ((JSONObject) weatherObj.get(0)).getString("description")); } } catch (Throwable e) { fetchStatus = NO_DATA; e.printStackTrace(); } } switch (fetchStatus) { case NO_DATA: WeatherData.newDataStatus = NO_DATA; break; case SERVER_ERROR: WeatherData.newDataStatus = SERVER_ERROR; break; case NO_NETWORK: WeatherData.newDataStatus = NO_NETWORK; break; } if (returnData == null) WeatherData.newDataStatus = NO_DATA; return returnData; }
From source file:net.freifunk.android.discover.model.Community.java
public void populate(final RequestQueue rq, final CommunityReady communityReady) { rq.add(new JsonObjectRequest(getDetailUrl(), null, new Response.Listener<JSONObject>() { @Override/*from ww w .j a v a2s. c om*/ public void onResponse(JSONObject jsonObject) { try { setApiName(jsonObject.getString("name")); setApi(jsonObject.getString("api")); if (jsonObject.has("metacommunity")) setMetacommunity(jsonObject.getString("metacommunity")); JSONObject location = jsonObject.getJSONObject("location"); setAddressCity(location.getString("city")); if (location.has("address")) { JSONObject address = jsonObject.getJSONObject("address"); if (address.has("Name")) setAddressName(address.getString("Name")); if (address.has("Street")) setAddressStreet(address.getString("Street")); if (address.has("Zipcode")) setAddressZipcode(address.getString("Zipcode")); } setLat(location.getDouble("lat")); setLon(location.getDouble("lon")); setUrl(jsonObject.getString("url")); Log.d(TAG, getCommunity().toString()); communityReady.ready(getCommunity()); } catch (JSONException e) { Log.e(TAG, e.toString()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Log.e(TAG, volleyError.toString()); } })); }
From source file:weathernotificationservice.wns.activities.MainActivity.java
private ParseResult parseTodayJson(String result) { try {/*from w ww . j a v a2s. c om*/ JSONObject reader = new JSONObject(result); final String code = reader.optString("cod"); if ("404".equals(code)) { return ParseResult.CITY_NOT_FOUND; } String city = reader.getString("name"); String country = ""; JSONObject countryObj = reader.optJSONObject("sys"); if (countryObj != null) { country = countryObj.getString("country"); todayWeather.setSunrise(countryObj.getString("sunrise")); todayWeather.setSunset(countryObj.getString("sunset")); } todayWeather.setCity(city); todayWeather.setCountry(country); JSONObject coordinates = reader.getJSONObject("coord"); if (coordinates != null) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); sp.edit().putFloat("latitude", (float) coordinates.getDouble("lon")) .putFloat("longitude", (float) coordinates.getDouble("lat")).commit(); } JSONObject main = reader.getJSONObject("main"); todayWeather.setTemperature(main.getString("temp")); todayWeather.setDescription(reader.getJSONArray("weather").getJSONObject(0).getString("description")); JSONObject windObj = reader.getJSONObject("wind"); todayWeather.setWind(windObj.getString("speed")); if (windObj.has("deg")) { todayWeather.setWindDirectionDegree(windObj.getDouble("deg")); } else { Log.e("parseTodayJson", "No wind direction available"); todayWeather.setWindDirectionDegree(null); } todayWeather.setPressure(main.getString("pressure")); todayWeather.setHumidity(main.getString("humidity")); JSONObject rainObj = reader.optJSONObject("rain"); String rain; if (rainObj != null) { rain = getRainString(rainObj); } else { JSONObject snowObj = reader.optJSONObject("snow"); if (snowObj != null) { rain = getRainString(snowObj); } else { rain = "0"; } } todayWeather.setRain(rain); final String idString = reader.getJSONArray("weather").getJSONObject(0).getString("id"); todayWeather.setId(idString); todayWeather.setIcon( setWeatherIcon(Integer.parseInt(idString), Calendar.getInstance().get(Calendar.HOUR_OF_DAY))); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this) .edit(); editor.putString("lastToday", result); editor.commit(); } catch (JSONException e) { Log.e("JSONException Data", result); e.printStackTrace(); return ParseResult.JSON_EXCEPTION; } return ParseResult.OK; }
From source file:weathernotificationservice.wns.activities.MainActivity.java
public ParseResult parseLongTermJson(String result) { int i;/* w w w . jav a 2 s. c om*/ try { JSONObject reader = new JSONObject(result); final String code = reader.optString("cod"); if ("404".equals(code)) { if (longTermWeather == null) { longTermWeather = new ArrayList<>(); longTermTodayWeather = new ArrayList<>(); longTermTomorrowWeather = new ArrayList<>(); } return ParseResult.CITY_NOT_FOUND; } longTermWeather = new ArrayList<>(); longTermTodayWeather = new ArrayList<>(); longTermTomorrowWeather = new ArrayList<>(); JSONArray list = reader.getJSONArray("list"); for (i = 0; i < list.length(); i++) { Weather weather = new Weather(); JSONObject listItem = list.getJSONObject(i); JSONObject main = listItem.getJSONObject("main"); weather.setDate(listItem.getString("dt")); weather.setTemperature(main.getString("temp")); weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description")); JSONObject windObj = listItem.optJSONObject("wind"); if (windObj != null) { weather.setWind(windObj.getString("speed")); weather.setWindDirectionDegree(windObj.getDouble("deg")); } weather.setPressure(main.getString("pressure")); weather.setHumidity(main.getString("humidity")); JSONObject rainObj = listItem.optJSONObject("rain"); String rain = ""; if (rainObj != null) { rain = getRainString(rainObj); } else { JSONObject snowObj = listItem.optJSONObject("snow"); if (snowObj != null) { rain = getRainString(snowObj); } else { rain = "0"; } } weather.setRain(rain); final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id"); weather.setId(idString); final String dateMsString = listItem.getString("dt") + "000"; Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(Long.parseLong(dateMsString)); weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY))); Calendar today = Calendar.getInstance(); if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) { longTermTodayWeather.add(weather); } else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) { longTermTomorrowWeather.add(weather); } else { longTermWeather.add(weather); } } SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this) .edit(); editor.putString("lastLongterm", result); editor.commit(); } catch (JSONException e) { Log.e("JSONException Data", result); e.printStackTrace(); return ParseResult.JSON_EXCEPTION; } return ParseResult.OK; }
From source file:org.protorabbit.json.DefaultSerializer.java
@SuppressWarnings("unchecked") void invokeMethod(Method[] methods, String key, String name, JSONObject jo, Object targetObject) { Object param = null;// www. ja v a2 s. com Throwable ex = null; for (int i = 0; i < methods.length; i++) { Method m = methods[i]; if (m.getName().equals(name)) { Class<?>[] paramTypes = m.getParameterTypes(); if (paramTypes.length == 1 && jo.has(key)) { Class<?> tparam = paramTypes[0]; boolean allowNull = false; try { if (jo.isNull(key)) { // do nothing because param is already null : lets us not null on other types } else if (Long.class.isAssignableFrom(tparam) || tparam == long.class) { param = new Long(jo.getLong(key)); } else if (Double.class.isAssignableFrom(tparam) || tparam == double.class) { param = new Double(jo.getDouble(key)); } else if (Integer.class.isAssignableFrom(tparam) || tparam == int.class) { param = new Integer(jo.getInt(key)); } else if (String.class.isAssignableFrom(tparam)) { param = jo.getString(key); } else if (Enum.class.isAssignableFrom(tparam)) { param = Enum.valueOf((Class<? extends Enum>) tparam, jo.getString(key)); } else if (Boolean.class.isAssignableFrom(tparam)) { param = new Boolean(jo.getBoolean(key)); } else if (jo.isNull(key)) { param = null; allowNull = true; } else if (Collection.class.isAssignableFrom(tparam)) { if (m.getGenericParameterTypes().length > 0) { Type t = m.getGenericParameterTypes()[0]; if (t instanceof ParameterizedType) { ParameterizedType tv = (ParameterizedType) t; if (tv.getActualTypeArguments().length > 0 && tv.getActualTypeArguments()[0] == String.class) { List<String> ls = new ArrayList<String>(); JSONArray ja = jo.optJSONArray(key); if (ja != null) { for (int j = 0; j < ja.length(); j++) { ls.add(ja.getString(j)); } } param = ls; } else if (tv.getActualTypeArguments().length == 1) { ParameterizedType type = (ParameterizedType) tv.getActualTypeArguments()[0]; Class itemClass = (Class) type.getRawType(); if (itemClass == Map.class && type.getActualTypeArguments().length == 2 && type.getActualTypeArguments()[0] == String.class && type.getActualTypeArguments()[1] == Object.class) { List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>(); JSONArray ja = jo.optJSONArray(key); if (ja != null) { for (int j = 0; j < ja.length(); j++) { Map<String, Object> map = new HashMap<String, Object>(); JSONObject mo = ja.getJSONObject(j); Iterator<String> keys = mo.keys(); while (keys.hasNext()) { String okey = keys.next(); Object ovalue = null; // make sure we don't get JSONObject$Null if (!mo.isNull(okey)) { ovalue = mo.get(okey); } map.put(okey, ovalue); } ls.add(map); } } param = ls; } else { getLogger().warning( "Don't know how to handle Collection of type : " + itemClass); } } else { getLogger().warning("Don't know how to handle Collection of type : " + tv.getActualTypeArguments()[0]); } } } } else { getLogger().warning( "Unable to serialize " + key + " : Don't know how to handle " + tparam); } } catch (JSONException e) { e.printStackTrace(); } if (param != null || allowNull) { try { if (m != null) { Object[] args = { param }; m.invoke(targetObject, args); ex = null; break; } } catch (SecurityException e) { ex = e; } catch (IllegalArgumentException e) { ex = e; } catch (IllegalAccessException e) { ex = e; } catch (InvocationTargetException e) { ex = e; } } } } } if (ex != null) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { throw new RuntimeException(ex); } } }
From source file:net.olejon.mdapp.PharmaciesLocationMapActivity.java
@Override public void onMapReady(final GoogleMap googleMap) { googleMap.setMyLocationEnabled(true); try {/*from w w w . j ava2 s . c o m*/ mTools.showToast(getString(R.string.pharmacies_location_map_locating), 0); RequestQueue requestQueue = Volley.newRequestQueue(mContext); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getString(R.string.project_website_uri) + "api/1/geocode/?address=" + URLEncoder.encode(mPharmacyAddress, "utf-8"), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { double latitude = response.getDouble("latitude"); double longitude = response.getDouble("longitude"); googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)) .title(mPharmacyName)); googleMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 16)); } catch (Exception e) { mTools.showToast( getString(R.string.pharmacies_location_map_exact_location_not_found), 1); Log.e("PharmaciesLocationMap", Log.getStackTraceString(e)); finish(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mTools.showToast(getString(R.string.pharmacies_location_map_exact_location_not_found), 1); Log.e("PharmaciesLocationMap", error.toString()); finish(); } }); jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); requestQueue.add(jsonObjectRequest); } catch (Exception e) { Log.e("PharmaciesLocationMap", Log.getStackTraceString(e)); } }
From source file:org.kavaproject.kavatouch.internal.ImageScaleModifier.java
public static ImageScaleModifier createFromJSON(JSONObject jModifier) throws JSONException { return new ImageScaleModifier(jModifier.getString("name"), (float) jModifier.getDouble("scale")); }