List of usage examples for org.json JSONArray getJSONObject
public JSONObject getJSONObject(int index) throws JSONException
From source file:com.aniruddhc.acemusic.player.GMusicHelpers.WebClientPlaylistsSchema.java
@Override public ArrayList<WebClientSongsSchema> fromJsonArray(JSONArray jsonArray) { ArrayList<WebClientSongsSchema> songList = new ArrayList<WebClientSongsSchema>(); if (jsonArray != null && jsonArray.length() > 0) { for (int i = 0; i < jsonArray.length(); i++) { try { WebClientSongsSchema song = new WebClientSongsSchema() .fromJsonObject(jsonArray.getJSONObject(i)); songList.add(song);//from w w w .ja v a2 s . co m } catch (JSONException e) { e.printStackTrace(); } } } return songList; }
From source file:org.runnerup.export.format.RunKeeper.java
private static SortedMap<Long, HashMap<String, String>> createPointsMap(JSONArray distance, JSONArray path, JSONArray hr) throws JSONException { SortedMap<Long, HashMap<String, String>> result = new TreeMap<Long, HashMap<String, String>>(); if (distance != null && distance.length() > 0) { for (int i = 0; i < distance.length(); i++) { JSONObject o = distance.getJSONObject(i); Long key = TimeUnit.SECONDS.toMillis((long) Float.parseFloat(o.getString("timestamp"))); HashMap<String, String> value = new HashMap<String, String>(); String valueMapKey = "distance"; String valueMapValue = o.getString(valueMapKey); value.put(valueMapKey, valueMapValue); result.put(key, value);// w w w.j av a 2 s . c o m } } if (path != null && path.length() > 0) { for (int i = 0; i < path.length(); i++) { JSONObject o = path.getJSONObject(i); Long key = TimeUnit.SECONDS.toMillis((long) Float.parseFloat(o.getString("timestamp"))); HashMap<String, String> value = result.get(key); if (value == null) { value = new HashMap<String, String>(); } String[] attrs = new String[] { "latitude", "longitude", "altitude", "type" }; for (String valueMapKey : attrs) { String valueMapValue = o.getString(valueMapKey); value.put(valueMapKey, valueMapValue); } result.put(key, value); } } if (hr != null && hr.length() > 0) { for (int i = 0; i < hr.length(); i++) { JSONObject o = hr.getJSONObject(i); Long key = TimeUnit.SECONDS.toMillis((long) Float.parseFloat(o.getString("timestamp"))); HashMap<String, String> value = result.get(key); if (value == null) { value = new HashMap<String, String>(); } String valueMapKey = "heart_rate"; String valueMapValue = o.getString(valueMapKey); value.put(valueMapKey, valueMapValue); result.put(key, value); } } return result; }
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./* ww w. ja va2s .co 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:run.ace.IncomingMessages.java
public static void set(JSONArray message) throws JSONException { Object instance = Handle.deserialize(message.getJSONObject(1)); String propertyName = message.getString(2); Object propertyValue = message.get(3); // Convert non-primitives (TODO arrays) if (propertyValue instanceof JSONObject) { propertyValue = Utils.deserializeObjectOrStruct((JSONObject) propertyValue); } else if (propertyValue == JSONObject.NULL) { propertyValue = null;//w w w. j av a 2s . co m } try { if (instance instanceof IHaveProperties) { ((IHaveProperties) instance).setProperty(propertyName, propertyValue); } else { // Try reflection. So XXX.YYY maps to a setYYY method. try { String setterName = "set"; if (propertyName.contains(".")) { setterName += propertyName.substring(propertyName.lastIndexOf(".") + 1); } else { setterName += propertyName; } //TODO: Need to do more permissive parameter matching in this case since everything will be strings. // Started to add this with looseMatching param. Continue. try { Integer value = Integer.parseInt(propertyValue.toString()); propertyValue = value; } catch (java.lang.NumberFormatException nfe) { try { Double value = Double.parseDouble(propertyValue.toString()); propertyValue = value; } catch (java.lang.NumberFormatException nfe2) { // Keep as string } } // TODO: Enable marshaling of things like "red" to Drawable... Utils.invokeMethodWithBestParameterMatch(instance.getClass(), setterName, instance, new Object[] { propertyValue }, true); } catch (Exception ex) { // // Translate standard cross-platform (XAML) properties for well-known base types // if (instance instanceof TextView) { if (propertyName.endsWith(".Children") && propertyValue instanceof ItemCollection) { // This is from XAML compilation of a custom content property, which always gives an ItemCollection. propertyName = "ContentControl.Content"; if (((ItemCollection) propertyValue).size() == 1) { propertyValue = ((ItemCollection) propertyValue).get(0); } } if (!TextViewHelper.setProperty((TextView) instance, propertyName, propertyValue)) { throw new RuntimeException("Unhandled property for a custom TextView: " + propertyName + ". Implement IHaveProperties to support this."); } } else if (instance instanceof ViewGroup) { if (propertyName.endsWith(".Children") && propertyValue instanceof ItemCollection) { // This is from XAML compilation of a custom content property, which always gives an ItemCollection. ItemCollection children = (ItemCollection) propertyValue; for (int i = 0; i < children.size(); i++) { ((ViewGroup) instance).addView((View) children.get(i)); } } else if (!ViewGroupHelper.setProperty((ViewGroup) instance, propertyName, propertyValue)) { throw new RuntimeException("Unhandled property for a custom ViewGroup: " + propertyName + ". Implement IHaveProperties to support this."); } } else if (instance instanceof View) { if (!ViewHelper.setProperty((View) instance, propertyName, propertyValue, true)) { throw new RuntimeException("Unhandled property for a custom View: " + propertyName + ". Implement IHaveProperties to support this."); } } else { throw new RuntimeException("Either there must be a set" + propertyName + " method, or IHaveProperties must be implemented."); } } } } catch (Exception ex) { throw new RuntimeException("Error setting " + instance.getClass().getSimpleName() + "'s " + propertyName + " to " + propertyValue, ex); } }
From source file:run.ace.IncomingMessages.java
public static Object invoke(JSONArray message) throws JSONException { Object instance = Handle.deserialize(message.getJSONObject(1)); String methodName = message.getString(2); JSONArray array = message.getJSONArray(3); return Utils.invokeMethod(instance.getClass(), instance, methodName, array); }
From source file:run.ace.IncomingMessages.java
public static Object fieldGet(JSONArray message) throws JSONException { Object instance = Handle.deserialize(message.getJSONObject(1)); String fieldName = message.getString(2); return Utils.getField(instance.getClass(), instance, fieldName); }
From source file:run.ace.IncomingMessages.java
public static Object privateFieldGet(JSONArray message) throws JSONException { Object instance = Handle.deserialize(message.getJSONObject(1)); String fieldName = message.getString(2); return Utils.getPrivateField(instance.getClass(), instance, fieldName); }
From source file:run.ace.IncomingMessages.java
public static void fieldSet(JSONArray message) throws JSONException { Object instance = Handle.deserialize(message.getJSONObject(1)); String fieldName = message.getString(2); Object fieldValue = message.get(3); // Convert non-primitives if (fieldValue instanceof JSONObject) { fieldValue = Utils.deserializeObjectOrStruct((JSONObject) fieldValue); } else if (fieldValue == JSONObject.NULL) { fieldValue = null;/*from w ww .j a v a 2s . c o m*/ } Utils.setField(instance.getClass(), instance, fieldName, fieldValue); }
From source file:run.ace.IncomingMessages.java
public static void eventAdd(JSONArray message) throws JSONException { Handle handle = Handle.fromJSONObject(message.getJSONObject(1)); Object instance = Handle.toObject(handle); String eventName = message.getString(2); if (instance instanceof IFireEvents) { ((IFireEvents) instance).addEventHandler(eventName, handle); } else if (!NativeEventAttacher.attach(instance, eventName, handle)) { throw new RuntimeException("Attaching handler for " + eventName + ", but it's not recognized and " + instance + " doesn't support IFireEvents."); }//from ww w . j av a 2s .c o m }
From source file:run.ace.IncomingMessages.java
public static void eventRemove(JSONArray message) throws JSONException { Object instance = Handle.deserialize(message.getJSONObject(1)); String eventName = message.getString(2); if (instance instanceof IFireEvents) { ((IFireEvents) instance).removeEventHandler(eventName); } else if (!NativeEventAttacher.detach(instance, eventName)) { throw new RuntimeException("Removing handler for " + eventName + ", but it's not recognized and " + instance + " doesn't support IFireEvents."); }// w w w . j a v a 2s .com }