List of usage examples for org.json JSONObject getDouble
public double getDouble(String key) throws JSONException
From source file:com.seunghyo.sunshine.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us./*from w ww . j a va 2s . c o m*/ */ private String[] getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } // add to database if (cVVector.size() > 0) { // Student: call bulkInsert to add the weatherEntries to the database here } // Sort order: Ascending, by date. String sortOrder = WeatherEntry.COLUMN_DATE + " ASC"; Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis()); // Students: Uncomment the next lines to display what what you stored in the bulkInsert // Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, // null, null, null, sortOrder); // // cVVector = new Vector<ContentValues>(cur.getCount()); // if ( cur.moveToFirst() ) { // do { // ContentValues cv = new ContentValues(); // DatabaseUtils.cursorRowToContentValues(cur, cv); // cVVector.add(cv); // } while (cur.moveToNext()); // } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted"); String[] resultStrs = convertContentValuesToUXFormat(cVVector); return resultStrs; } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; }
From source file:com.google.blockly.model.FieldNumber.java
public static FieldNumber fromJson(JSONObject json) throws BlockLoadingException { String name = json.optString("name", null); if (name == null) { throw new BlockLoadingException("Number fields must have name field."); }/*w ww . j av a2 s. c o m*/ FieldNumber field = new FieldNumber(name); if (json.has("value")) { try { field.setValue(json.getDouble("value")); } catch (JSONException e) { throw new BlockLoadingException( "Cannot parse field_number value: " + json.optString("value", "[object or array]")); } } try { field.setConstraints(json.optDouble("min", NO_CONSTRAINT), json.optDouble("max", NO_CONSTRAINT), json.optDouble("precision", NO_CONSTRAINT)); } catch (IllegalArgumentException e) { throw new BlockLoadingException(e); } return field; }
From source file:be.brunoparmentier.openbikesharing.app.parsers.BikeNetworksListParser.java
public BikeNetworksListParser(String toParse) throws ParseException { bikeNetworks = new ArrayList<>(); try {/*from w w w . j a va 2s.c om*/ JSONObject jsonObject = new JSONObject(toParse); JSONArray rawNetworks = jsonObject.getJSONArray("networks"); for (int i = 0; i < rawNetworks.length(); i++) { JSONObject rawNetwork = rawNetworks.getJSONObject(i); String id = rawNetwork.getString("id"); String name = rawNetwork.getString("name"); String company = rawNetwork.getString("company"); BikeNetworkLocation location; /* network location */ { JSONObject rawLocation = rawNetwork.getJSONObject("location"); double latitude = rawLocation.getDouble("latitude"); double longitude = rawLocation.getDouble("longitude"); String city = rawLocation.getString("city"); String country = rawLocation.getString("country"); location = new BikeNetworkLocation(latitude, longitude, city, country); } bikeNetworks.add(new BikeNetworkInfo(id, name, company, location)); } } catch (JSONException e) { throw new ParseException("Error parsing JSON", 0); } }
From source file:com.goliathonline.android.kegbot.io.RemoteDrinksHandler.java
/** {@inheritDoc} */ @Override/* w ww .ja va 2 s . c o m*/ public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver) throws JSONException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Walk document, parsing any incoming entries int drink_id = 0; JSONObject result = parser.getJSONObject("result"); JSONArray drinks = result.getJSONArray("drinks"); JSONObject drink; for (int i = 0; i < drinks.length(); i++) { if (drink_id == 0) { // && ENTRY.equals(parser.getName() // Process single spreadsheet row at a time drink = drinks.getJSONObject(i); final String drinkId = sanitizeId(drink.getString("id")); final Uri drinkUri = Drinks.buildDrinkUri(drinkId); // Check for existing details, only update when changed final ContentValues values = queryDrinkDetails(drinkUri, resolver); final long localUpdated = values.getAsLong(SyncColumns.UPDATED); final long serverUpdated = 500; //entry.getUpdated(); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "found drink " + drinkId); Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated); } if (localUpdated != KegbotContract.UPDATED_NEVER) continue; final Uri drinkKegUri = Drinks.buildKegUri(drinkId); final Uri drinkUserUri = Drinks.buildUserUri(drinkId); // Clear any existing values for this session, treating the // incoming details as authoritative. batch.add(ContentProviderOperation.newDelete(drinkUri).build()); batch.add(ContentProviderOperation.newDelete(drinkKegUri).build()); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Drinks.CONTENT_URI); builder.withValue(SyncColumns.UPDATED, serverUpdated); builder.withValue(Drinks.DRINK_ID, drinkId); // Inherit starred value from previous row if (values.containsKey(Drinks.DRINK_STARRED)) { builder.withValue(Drinks.DRINK_STARRED, values.getAsInteger(Drinks.DRINK_STARRED)); } if (drink.has("session_id")) builder.withValue(Drinks.SESSION_ID, drink.getInt("session_id")); if (drink.has("status")) builder.withValue(Drinks.STATUS, drink.getString("status")); if (drink.has("user_id")) builder.withValue(Drinks.USER_ID, drink.getString("user_id")); if (drink.has("keg_id")) builder.withValue(Drinks.KEG_ID, drink.getInt("keg_id")); if (drink.has("volume_ml")) builder.withValue(Drinks.VOLUME, drink.getDouble("volume_ml")); if (drink.has("pour_time")) builder.withValue(Drinks.POUR_TIME, drink.getString("pour_time")); // Normal session details ready, write to provider batch.add(builder.build()); // Assign kegs final int kegId = drink.getInt("keg_id"); batch.add(ContentProviderOperation.newInsert(drinkKegUri).withValue(DrinksKeg.DRINK_ID, drinkId) .withValue(DrinksKeg.KEG_ID, kegId).build()); // Assign users if (drink.has("user_id")) { final String userId = drink.getString("user_id"); batch.add(ContentProviderOperation.newInsert(drinkUserUri) .withValue(DrinksUser.DRINK_ID, drinkId).withValue(DrinksUser.USER_ID, userId).build()); } } } return batch; }
From source file:uk.co.senab.photup.model.Place.java
public Place(JSONObject object, Account account) throws JSONException { super(object, account); mCategory = object.getString("category"); JSONObject location = object.getJSONObject("location"); mLatitude = location.getDouble("latitude"); mLongitude = location.getDouble("longitude"); }
From source file:com.sonoport.freesound.response.mapping.Mapper.java
/** * Extract a named value from a {@link JSONObject}. This method checks whether the value exists and is not an * instance of <code>JSONObject.NULL</code>. * * @param jsonObject The {@link JSONObject} being processed * @param field The field to retrieve/*www. j a v a 2 s.c o m*/ * @param fieldType The data type of the field * @return The field value (or null if not found) * * @param <T> The data type to return */ @SuppressWarnings("unchecked") protected <T extends Object> T extractFieldValue(final JSONObject jsonObject, final String field, final Class<T> fieldType) { T fieldValue = null; if ((jsonObject != null) && jsonObject.has(field) && !jsonObject.isNull(field)) { try { if (fieldType == String.class) { fieldValue = (T) jsonObject.getString(field); } else if (fieldType == Integer.class) { fieldValue = (T) Integer.valueOf(jsonObject.getInt(field)); } else if (fieldType == Long.class) { fieldValue = (T) Long.valueOf(jsonObject.getLong(field)); } else if (fieldType == Float.class) { fieldValue = (T) Float.valueOf(Double.toString(jsonObject.getDouble(field))); } else if (fieldType == JSONArray.class) { fieldValue = (T) jsonObject.getJSONArray(field); } else if (fieldType == JSONObject.class) { fieldValue = (T) jsonObject.getJSONObject(field); } else { fieldValue = (T) jsonObject.get(field); } } catch (final JSONException | ClassCastException e) { // TODO Log a warning } } return fieldValue; }
From source file:com.ibm.iot.android.iotstarter.utils.MessageConductor.java
/** * Steer incoming MQTT messages to the proper activities based on their content. * * @param payload The log of the MQTT message. * @param topic The topic the MQTT message was received on. * @throws JSONException If the message contains invalid JSON. *//*from w w w.j a v a 2 s .c om*/ public void steerMessage(String payload, String topic) throws JSONException { Log.d(TAG, ".steerMessage() entered"); JSONObject top = new JSONObject(payload); JSONObject d = top.getJSONObject("d"); if (topic.contains(Constants.COLOR_EVENT)) { Log.d(TAG, "Color Event"); int r = d.getInt("r"); int g = d.getInt("g"); int b = d.getInt("b"); // alpha value received is 0.0 < a < 1.0 but Color.argb expects 0 < a < 255 int alpha = (int) (d.getDouble("alpha") * 255.0); if ((r > 255 || r < 0) || (g > 255 || g < 0) || (b > 255 || b < 0) || (alpha > 255 || alpha < 0)) { return; } app.setColor(Color.argb(alpha, r, g, b)); Intent actionIntent = new Intent(Constants.APP_ID + Constants.INTENT_IOT); actionIntent.putExtra(Constants.INTENT_DATA, Constants.COLOR_EVENT); context.sendBroadcast(actionIntent); } else if (topic.contains(Constants.FRE_EVENT)) { JSONObject topp = new JSONObject(payload); JSONObject dd = topp.getJSONObject("d"); int frequency = dd.getInt("f"); Log.d("MMM", "" + frequency); app.setFfe(frequency); } else if (topic.contains(Constants.LIGHT_EVENT)) { app.handleLightMessage(); } else if (topic.contains(Constants.TEXT_EVENT)) { int unreadCount = app.getUnreadCount(); String messageText = d.getString("text"); app.setUnreadCount(++unreadCount); // Log message with the following format: // [yyyy-mm-dd hh:mm:ss.S] Received text: // <message text> Date date = new Date(); String logMessage = "[" + new Timestamp(date.getTime()) + "] Received Text:\n"; app.getMessageLog().add(logMessage + messageText); // Send intent to LOG fragment to mark list data invalidated String runningActivity = app.getCurrentRunningActivity(); //if (runningActivity != null && runningActivity.equals(LogPagerFragment.class.getName())) { Intent actionIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOG); actionIntent.putExtra(Constants.INTENT_DATA, Constants.TEXT_EVENT); context.sendBroadcast(actionIntent); //} // Send intent to current active fragment / activity to update Unread message count // Skip sending intent if active tab is LOG // TODO: 'current activity' code needs fixing. Intent unreadIntent; if (runningActivity.equals(LogPagerFragment.class.getName())) { unreadIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOG); } else if (runningActivity.equals(LoginPagerFragment.class.getName())) { unreadIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOGIN); } else if (runningActivity.equals(IoTPagerFragment.class.getName())) { unreadIntent = new Intent(Constants.APP_ID + Constants.INTENT_IOT); } else if (runningActivity.equals(ProfilesActivity.class.getName())) { unreadIntent = new Intent(Constants.APP_ID + Constants.INTENT_PROFILES); } else { return; } if (messageText != null) { unreadIntent.putExtra(Constants.INTENT_DATA, Constants.UNREAD_EVENT); context.sendBroadcast(unreadIntent); } } else if (topic.contains(Constants.ALERT_EVENT)) { // save payload in an arrayList int unreadCount = app.getUnreadCount(); String messageText = d.getString("text"); app.setUnreadCount(++unreadCount); // Log message with the following format: // [yyyy-mm-dd hh:mm:ss.S] Received alert: // <message text> Date date = new Date(); String logMessage = "[" + new Timestamp(date.getTime()) + "] Received Alert:\n"; app.getMessageLog().add(logMessage + messageText); String runningActivity = app.getCurrentRunningActivity(); if (runningActivity != null) { //if (runningActivity.equals(LogPagerFragment.class.getName())) { Intent actionIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOG); actionIntent.putExtra(Constants.INTENT_DATA, Constants.TEXT_EVENT); context.sendBroadcast(actionIntent); //} // Send alert intent with message payload to current active activity / fragment. // TODO: update for current activity changes. Intent alertIntent; if (runningActivity.equals(LogPagerFragment.class.getName())) { alertIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOG); } else if (runningActivity.equals(LoginPagerFragment.class.getName())) { alertIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOGIN); } else if (runningActivity.equals(IoTPagerFragment.class.getName())) { alertIntent = new Intent(Constants.APP_ID + Constants.INTENT_IOT); } else if (runningActivity.equals(ProfilesActivity.class.getName())) { alertIntent = new Intent(Constants.APP_ID + Constants.INTENT_PROFILES); } else { return; } if (messageText != null) { alertIntent.putExtra(Constants.INTENT_DATA, Constants.ALERT_EVENT); alertIntent.putExtra(Constants.INTENT_DATA_MESSAGE, d.getString("text")); context.sendBroadcast(alertIntent); } } } }
From source file:com.github.cambierr.lorawanpacket.semtech.Txpk.java
public Txpk(JSONObject _json) throws MalformedPacketException { /**/*from w ww . ja v a2s . co m*/ * imme */ if (!_json.has("imme")) { imme = false; } else { imme = _json.getBoolean("imme"); } /** * tmst */ if (!_json.has("tmst")) { tmst = Integer.MAX_VALUE; } else { tmst = _json.getInt("tmst"); } /** * time */ if (!_json.has("time")) { time = null; } else { time = _json.getString("time"); } /** * rfch */ if (!_json.has("rfch")) { throw new MalformedPacketException("missing rfch"); } else { rfch = _json.getInt("rfch"); } /** * freq */ if (!_json.has("freq")) { throw new MalformedPacketException("missing freq"); } else { freq = _json.getDouble("stat"); } /** * powe */ if (!_json.has("powe")) { throw new MalformedPacketException("missing powe"); } else { powe = _json.getInt("powe"); } /** * modu */ if (!_json.has("modu")) { throw new MalformedPacketException("missing modu"); } else { modu = Modulation.parse(_json.getString("modu")); } /** * datr */ if (!_json.has("datr")) { throw new MalformedPacketException("missing datr"); } else { switch (modu) { case FSK: datr = _json.getInt("datr"); break; case LORA: datr = _json.getString("datr"); break; } } /** * codr */ if (!_json.has("codr")) { if (modu.equals(Modulation.FSK)) { codr = null; } else { throw new MalformedPacketException("missing codr"); } } else { codr = _json.getString("codr"); } /** * fdev */ if (!_json.has("fdev")) { if (modu.equals(Modulation.LORA)) { fdev = Integer.MAX_VALUE; } else { throw new MalformedPacketException("missing fdev"); } } else { fdev = _json.getInt("fdev"); } /** * ipol */ if (!_json.has("ipol")) { if (modu.equals(Modulation.FSK)) { ipol = false; } else { throw new MalformedPacketException("missing ipol"); } } else { ipol = _json.getBoolean("ipol"); } /** * prea */ if (!_json.has("prea")) { throw new MalformedPacketException("missing prea"); } else { prea = _json.getInt("prea"); } /** * size */ if (!_json.has("size")) { throw new MalformedPacketException("missing size"); } else { size = _json.getInt("size"); } /** * data */ if (!_json.has("data")) { throw new MalformedPacketException("missing data"); } else { byte[] raw; try { raw = Base64.getDecoder().decode(_json.getString("data")); } catch (IllegalArgumentException ex) { throw new MalformedPacketException("malformed data"); } data = new PhyPayload(ByteBuffer.wrap(raw)); } /** * ncrc */ if (!_json.has("ncrc")) { ncrc = false; } else { ncrc = _json.getBoolean("ncrc"); } }
From source file:com.richtodd.android.quiltdesign.block.PaperPiecedBlockPiece.java
static final PaperPiecedBlockPiece createFromJSONObject(JSONObject jsonObject) throws JSONException { PointF from = new PointF((float) jsonObject.getDouble("from_x"), (float) jsonObject.getDouble("from_y")); PointF to = new PointF((float) jsonObject.getDouble("to_x"), (float) jsonObject.getDouble("to_y")); int color = jsonObject.getInt("color"); PaperPiecedBlockPiece piece = new PaperPiecedBlockPiece(from, to, color); return piece; }
From source file:com.nginious.http.application.Http11SerializerTestCase.java
private void testResponse(String body) throws Exception { JSONObject bean = new JSONObject(body); assertTrue(bean.has("testBean1")); bean = bean.getJSONObject("testBean1"); assertEquals(true, bean.getBoolean("first")); assertEquals(1.1d, bean.getDouble("second")); assertEquals(1.2f, (float) bean.getDouble("third")); assertEquals(2, bean.getInt("fourth")); assertEquals(5L, bean.getLong("fifth")); assertEquals((short) 3, (short) bean.getInt("sixth")); assertEquals("Seven", bean.getString("seventh")); assertTrue(bean.has("eight")); assertTrue(bean.has("ninth")); }