List of usage examples for org.json JSONObject getLong
public long getLong(String key) throws JSONException
From source file:com.facebook.internal.BundleJSONConverterTest.java
@Test public void testSimpleValues() throws JSONException { ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("1st"); arrayList.add("2nd"); arrayList.add("third"); Bundle innerBundle1 = new Bundle(); innerBundle1.putInt("inner", 1); Bundle innerBundle2 = new Bundle(); innerBundle2.putString("inner", "2"); innerBundle2.putStringArray("deep list", new String[] { "7", "8" }); innerBundle1.putBundle("nested bundle", innerBundle2); Bundle b = new Bundle(); b.putBoolean("boolValue", true); b.putInt("intValue", 7); b.putLong("longValue", 5000000000l); b.putDouble("doubleValue", 3.14); b.putString("stringValue", "hello world"); b.putStringArray("stringArrayValue", new String[] { "first", "second" }); b.putStringArrayList("stringArrayListValue", arrayList); b.putBundle("nested", innerBundle1); JSONObject json = BundleJSONConverter.convertToJSON(b); assertNotNull(json);//from w ww.j a v a2s . c om assertEquals(true, json.getBoolean("boolValue")); assertEquals(7, json.getInt("intValue")); assertEquals(5000000000l, json.getLong("longValue")); assertEquals(3.14, json.getDouble("doubleValue"), TestUtils.DOUBLE_EQUALS_DELTA); assertEquals("hello world", json.getString("stringValue")); JSONArray jsonArray = json.getJSONArray("stringArrayValue"); assertEquals(2, jsonArray.length()); assertEquals("first", jsonArray.getString(0)); assertEquals("second", jsonArray.getString(1)); jsonArray = json.getJSONArray("stringArrayListValue"); assertEquals(3, jsonArray.length()); assertEquals("1st", jsonArray.getString(0)); assertEquals("2nd", jsonArray.getString(1)); assertEquals("third", jsonArray.getString(2)); JSONObject innerJson = json.getJSONObject("nested"); assertEquals(1, innerJson.getInt("inner")); innerJson = innerJson.getJSONObject("nested bundle"); assertEquals("2", innerJson.getString("inner")); jsonArray = innerJson.getJSONArray("deep list"); assertEquals(2, jsonArray.length()); assertEquals("7", jsonArray.getString(0)); assertEquals("8", jsonArray.getString(1)); Bundle finalBundle = BundleJSONConverter.convertToBundle(json); assertNotNull(finalBundle); assertEquals(true, finalBundle.getBoolean("boolValue")); assertEquals(7, finalBundle.getInt("intValue")); assertEquals(5000000000l, finalBundle.getLong("longValue")); assertEquals(3.14, finalBundle.getDouble("doubleValue"), TestUtils.DOUBLE_EQUALS_DELTA); assertEquals("hello world", finalBundle.getString("stringValue")); List<String> stringList = finalBundle.getStringArrayList("stringArrayValue"); assertEquals(2, stringList.size()); assertEquals("first", stringList.get(0)); assertEquals("second", stringList.get(1)); stringList = finalBundle.getStringArrayList("stringArrayListValue"); assertEquals(3, stringList.size()); assertEquals("1st", stringList.get(0)); assertEquals("2nd", stringList.get(1)); assertEquals("third", stringList.get(2)); Bundle finalInnerBundle = finalBundle.getBundle("nested"); assertEquals(1, finalInnerBundle.getInt("inner")); finalBundle = finalInnerBundle.getBundle("nested bundle"); assertEquals("2", finalBundle.getString("inner")); stringList = finalBundle.getStringArrayList("deep list"); assertEquals(2, stringList.size()); assertEquals("7", stringList.get(0)); assertEquals("8", stringList.get(1)); }
From source file:org.protorabbit.Config.java
@SuppressWarnings("unchecked") private void registerTemplates(ITemplate temp, JSONObject t, String baseURI) { try {/*w w w . ja va2 s.c o m*/ if (t.has("timeout")) { long templateTimeout = t.getLong("timeout"); temp.setTimeout(templateTimeout); } boolean tgzip = false; if (!devMode) { tgzip = gzip; } if (t.has("gzip")) { tgzip = t.getBoolean("gzip"); temp.setGzipStyles(tgzip); temp.setGzipScripts(tgzip); temp.setGzipTemplate(tgzip); } if (t.has("uniqueURL")) { Boolean unique = t.getBoolean("uniqueURL"); temp.setUniqueURL(unique); } // template overrides default combineResources if (t.has("combineResources")) { boolean combineResources = t.getBoolean("combineResources"); temp.setCombineResources(combineResources); temp.setCombineScripts(combineResources); temp.setCombineStyles(combineResources); } if (t.has("template")) { String turi = t.getString("template"); ResourceURI templateURI = new ResourceURI(turi, baseURI, ResourceURI.TEMPLATE); temp.setTemplateURI(templateURI); } if (t.has("namespace")) { temp.setURINamespace(t.getString("namespace")); } if (t.has("extends")) { List<String> ancestors = null; String base = t.getString("extends"); if (base.length() > 0) { String[] parentIds = null; if (base.indexOf(",") != -1) { parentIds = base.split(","); } else { parentIds = new String[1]; parentIds[0] = base; } ancestors = new ArrayList<String>(); for (int j = 0; j < parentIds.length; j++) { ancestors.add(parentIds[j].trim()); } } temp.setAncestors(ancestors); } if (t.has("overrides")) { List<TemplateOverride> overrides = new ArrayList<TemplateOverride>(); JSONArray joa = t.getJSONArray("overrides"); for (int z = 0; z < joa.length(); z++) { TemplateOverride tor = new TemplateOverride(); JSONObject toro = joa.getJSONObject(z); if (toro.has("test")) { tor.setTest(toro.getString("test")); } if (toro.has("uaTest")) { tor.setUATest(toro.getString("uaTest")); } if (toro.has("import")) { tor.setImportURI(toro.getString("import")); } overrides.add(tor); } temp.setTemplateOverrides(overrides); } if (t.has("scripts")) { JSONObject bsjo = t.getJSONObject("scripts"); processURIResources(ResourceURI.SCRIPT, bsjo, temp, baseURI); } if (t.has("styles")) { JSONObject bsjo = t.getJSONObject("styles"); processURIResources(ResourceURI.LINK, bsjo, temp, baseURI); } if (t.has("properties")) { Map<String, IProperty> properties = null; JSONObject po = t.getJSONObject("properties"); properties = new HashMap<String, IProperty>(); Iterator<String> jit = po.keys(); while (jit.hasNext()) { String name = jit.next(); JSONObject so = po.getJSONObject(name); int type = IProperty.STRING; String value = so.getString("value"); if (so.has("type")) { String typeString = so.getString("type"); if ("string".equals(typeString.toLowerCase())) { type = IProperty.STRING; } else if ("include".equals(typeString.toLowerCase())) { type = IProperty.INCLUDE; } } IProperty pi = new Property(name, value, type, baseURI, temp.getId()); if (so.has("timeout")) { long timeout = so.getLong("timeout"); pi.setTimeout(timeout); } if (so.has("id")) { pi.setId(so.getString("id")); } if (so.has("uaTest")) { pi.setUATest(so.getString("uaTest")); } if (so.has("test")) { pi.setTest(so.getString("test")); } if (so.has("defer")) { pi.setDefer(so.getBoolean("defer")); } if (so.has("deferContent")) { pi.setDeferContent(new StringBuffer(so.getString("deferContent"))); } properties.put(name, pi); } temp.setProperties(properties); } } catch (JSONException e) { getLogger().log(Level.SEVERE, "Error parsing configuration.", e); } }
From source file:com.swisscom.android.sunshine.data.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 w w. ja va 2 s .c o m*/ */ private Void getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting) throws JSONException { // 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"; final String OWM_COORD_LAT = "lat"; final String OWM_COORD_LONG = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_DATETIME = "dt"; 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"; 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 coordJSON = cityJson.getJSONObject(OWM_COORD); double cityLatitude = coordJSON.getLong(OWM_COORD_LAT); double cityLongitude = coordJSON.getLong(OWM_COORD_LONG); Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude); // Insert the location into the database. long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Get and insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); 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); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". dateTime = dayForecast.getLong(OWM_DATETIME); 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_DATETEXT, WeatherContract.getDbDateString(new Date(dateTime * 1000L))); 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); } if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); int rowsInserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); Log.v(LOG_TAG, "inserted " + rowsInserted + " rows of weather data"); } return null; }
From source file:cn.code.notes.gtask.remote.GTaskManager.java
private void addLocalNode(Node node) throws NetworkFailureException { if (mCancelled) { return;/* w ww .j a v a 2 s. co m*/ } SqlNote sqlNote; if (node instanceof TaskList) { if (node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) { sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); } else if (node.getName() .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); } else { sqlNote = new SqlNote(mContext); sqlNote.setContent(node.getLocalJSONFromContent()); sqlNote.setParentId(Notes.ID_ROOT_FOLDER); } } else { sqlNote = new SqlNote(mContext); JSONObject js = node.getLocalJSONFromContent(); try { if (js.has(GTaskStringUtils.META_HEAD_NOTE)) { JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); if (note.has(NoteColumns.ID)) { long id = note.getLong(NoteColumns.ID); if (DataUtils.existInNoteDatabase(mContentResolver, id)) { // the id is not available, have to create a new one note.remove(NoteColumns.ID); } } } if (js.has(GTaskStringUtils.META_HEAD_DATA)) { JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); for (int i = 0; i < dataArray.length(); i++) { JSONObject data = dataArray.getJSONObject(i); if (data.has(DataColumns.ID)) { long dataId = data.getLong(DataColumns.ID); if (DataUtils.existInDataDatabase(mContentResolver, dataId)) { // the data id is not available, have to create // a new one data.remove(DataColumns.ID); } } } } } catch (JSONException e) { Log.w(TAG, e.toString()); e.printStackTrace(); } sqlNote.setContent(js); Long parentId = mGidToNid.get(((Task) node).getParent().getGid()); if (parentId == null) { Log.e(TAG, "cannot find task's parent id locally"); throw new ActionFailureException("cannot add local node"); } sqlNote.setParentId(parentId.longValue()); } // create the local node sqlNote.setGtaskId(node.getGid()); sqlNote.commit(false); // update gid-nid mapping mGidToNid.put(node.getGid(), sqlNote.getId()); mNidToGid.put(sqlNote.getId(), node.getGid()); // update meta updateRemoteMeta(node.getGid(), sqlNote); }
From source file:fr.openbike.android.io.RemoteStationsSyncHandler.java
/** {@inheritDoc} */ @Override//from w ww . ja va2 s .co m public Object parse(JSONObject jsonBikes, OpenBikeDBAdapter dbAdapter) throws JSONException, IOException { long version = jsonBikes.getLong(VERSION); String message = jsonBikes.optString(MESSAGE); if (version > mCurrentVersion) { return null; } else { JSONArray stations = jsonBikes.optJSONArray(STATIONS); if (stations != null) { if (dbAdapter.syncStations(stations)) { // Need // Update return null; } } } return message; }
From source file:cn.code.notes.gtask.data.SqlData.java
public void setContent(JSONObject js) throws JSONException { long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; if (mIsCreate || mDataId != dataId) { mDiffDataValues.put(DataColumns.ID, dataId); }//w ww.j a v a 2 s . c o m mDataId = dataId; String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) : DataConstants.NOTE; if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); } mDataMimeType = dataMimeType; String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; if (mIsCreate || !mDataContent.equals(dataContent)) { mDiffDataValues.put(DataColumns.CONTENT, dataContent); } mDataContent = dataContent; long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; if (mIsCreate || mDataContentData1 != dataContentData1) { mDiffDataValues.put(DataColumns.DATA1, dataContentData1); } mDataContentData1 = dataContentData1; String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { mDiffDataValues.put(DataColumns.DATA3, dataContentData3); } mDataContentData3 = dataContentData3; }
From source file:fr.immotronic.ubikit.pems.enocean.impl.item.data.EEP0702xxDataImpl.java
public static EEP0702xxDataImpl constructDataFromRecord(JSONObject lastKnownData) { if (lastKnownData == null) return new EEP0702xxDataImpl(Float.MIN_VALUE, null); try {/* w w w. jav a2 s . co m*/ float temperature = (float) lastKnownData.getDouble("temperature"); Date date = new Date(lastKnownData.getLong("date")); return new EEP0702xxDataImpl(temperature, date); } catch (JSONException e) { Logger.error(LC.gi(), null, "constructDataFromRecord(): An exception while building a sensorData from a JSONObject SHOULD never happen. Check the code !", e); return new EEP0702xxDataImpl(Float.MIN_VALUE, null); } }
From source file:com.sublimis.urgentcallfilter.Magic.java
public static long jsonGetLong(JSONObject jsonObject, String name, long defValue) { long retVal = defValue; try {//from www . j a v a 2 s. c o m retVal = jsonObject.getLong(name); } catch (Exception e) { } return retVal; }
From source file:com.ichi2.anki2.DeckOptions.java
private void addMissingValues() { try {// ww w. ja v a 2s . c o m for (JSONObject o : mCol.getDecks().all()) { JSONObject conf = mCol.getDecks().confForDid(o.getLong("id")); if (!conf.has("replayq")) { conf.put("replayq", true); mCol.getDecks().save(conf); } } } catch (JSONException e1) { // nothing } }
From source file:com.example.kylelehman.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./* www . java 2 s.co m*/ */ private void getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting) throws JSONException { // 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"; final String OWM_COORD_LAT = "lat"; final String OWM_COORD_LONG = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_DATETIME = "dt"; 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"; 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 coordJSON = cityJson.getJSONObject(OWM_COORD); double cityLatitude = coordJSON.getLong(OWM_COORD_LAT); double cityLongitude = coordJSON.getLong(OWM_COORD_LONG); Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude); // Insert the location into the database. long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Get and insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); 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); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". dateTime = dayForecast.getLong(OWM_DATETIME); 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_DATETEXT, WeatherContract.getDbDateString(new Date(dateTime * 1000L))); 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); } if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } }