List of usage examples for org.json JSONArray length
public int length()
From source file:com.aerhard.oxygen.plugin.dbtagger.util.JsonUtil.java
/** * Gets table headers from the JSON server response. * //from ww w . j a va2 s . co m * @param responseJSON * the JSON response * @return the headers */ private String[] getTableHeaders(JSONObject responseJSON) { String[] cols = null; try { JSONArray colsArray = responseJSON.getJSONArray("cols"); cols = new String[colsArray.length()]; JSONObject fieldObj; for (int i = 0; i < colsArray.length(); i++) { fieldObj = (JSONObject) colsArray.get(i); cols[i] = fieldObj.optString("name"); } } catch (JSONException e) { workspace.showErrorMessage(i18n.getString("jsonUtil.columnNameError")); } return cols; }
From source file:com.aerhard.oxygen.plugin.dbtagger.util.JsonUtil.java
/** * Gets the table body in the JSON server response and calls * {@link #convertArray(int, int, JSONArray)}. * /*from ww w. ja v a2s .c om*/ * @param responseJSON * the JSON response * @return the body content */ private String[][] getTableBody(JSONObject responseJSON, int columns) { try { JSONArray dataArray = responseJSON.getJSONArray("data"); if (dataArray != null) { int rows = dataArray.length(); if (rows > 0) { return convertArray(rows, columns, dataArray); } } } catch (JSONException e) { workspace.showErrorMessage(i18n.getString("jsonUtil.dataError") + "\n" + e.toString()); } catch (ArrayStoreException e) { workspace.showErrorMessage(e.toString()); } return null; }
From source file:com.aerhard.oxygen.plugin.dbtagger.util.JsonUtil.java
/** * Converts a JSON array to from the JSON server response. * //from w w w . ja va 2s.com * @param columns * The number of columns. * @param rows * The number of rows. * @param dataArray * the input data. * * @return the body content */ private String[][] convertArray(int rows, int columns, JSONArray dataArray) { String[][] resultTable = new String[rows][]; for (int i = 0; i < rows; i++) { JSONArray arr = dataArray.getJSONArray(i); List<String> list = new ArrayList<String>(); if (arr.length() < columns) { throw new ArrayStoreException(i18n.getString("jsonUtil.dataColumnError")); } for (int j = 0; j < columns; j++) { list.add(arr.isNull(j) ? "" : arr.getString(j)); } resultTable[i] = list.toArray(new String[columns]); } return resultTable; }
From source file:conroller.CommentController.java
public static ArrayList<CommentModel> viewComment() throws IOException, JSONException { phpConnection.setConnection(//from www . j ava2 s . c o m "http://itmahaweliauthority.net23.net/MahaweliAuthority/CommentPHPfiles/CommentGetView.php"); String feedbackId, userName, typeOfUser, tankName, massage; ArrayList<CommentModel> arrayList = new ArrayList<>(); JSONObject jSONObject = new JSONObject(phpConnection.readData()); JSONArray array = jSONObject.getJSONArray("server_response"); for (int i = 0; i < array.length(); i++) { JSONObject details = array.getJSONObject(i); try { feedbackId = String.valueOf(details.getString("feedbackId")); } catch (Exception ex) { feedbackId = null; } try { userName = String.valueOf(details.getString("userName")); } catch (Exception ex) { userName = null; } try { typeOfUser = String.valueOf(details.getString("typeOfUser")); } catch (Exception ex) { typeOfUser = null; } try { tankName = String.valueOf(details.getString("tankName")); } catch (Exception ex) { tankName = null; } try { massage = String.valueOf(details.getString("massage")); } catch (Exception ex) { massage = null; } CommentModel model = new CommentModel(feedbackId, userName, typeOfUser, tankName, massage); arrayList.add(model); } return arrayList; }
From source file:de.knufficast.search.GPodderSearch.java
public void search(final String query, final BooleanCallback<List<Result>, String> callback) { runOnThread(new Runnable() { @Override// w w w.j a v a 2 s .c o m public void run() { String queryUrl = String.format(SEARCH_URL, URLEncoder.encode(query)); HttpGet request = new HttpGet(queryUrl); try { List<Result> results = new ArrayList<Result>(); JSONArray response = httpUtil.getJsonArray(request); int max = response.length(); for (int i = 0; i < max; i++) { JSONObject jsonResult = response.getJSONObject(i); GPodderResult result = new GPodderResult(); result.website = jsonResult.optString("website"); result.description = jsonResult.optString("description"); result.title = jsonResult.optString("title"); result.feedUrl = jsonResult.optString("url"); result.imgUrl = jsonResult.optString("scaled_logo_url"); results.add(result); } callback.success(results); } catch (IOException e) { callback.fail(ERROR_CONNECTION); } catch (JSONException e) { callback.fail(ERROR_JSON); } } }); }
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 . j a v a 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 initGTaskList() throws NetworkFailureException { if (mCancelled) return;/*from w ww . j a v a2 s . c om*/ GTaskClient client = GTaskClient.getInstance(); try { JSONArray jsTaskLists = client.getTaskLists(); // init meta list first mMetaList = null; for (int i = 0; i < jsTaskLists.length(); i++) { JSONObject object = jsTaskLists.getJSONObject(i); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { mMetaList = new TaskList(); mMetaList.setContentByRemoteJSON(object); // load meta data JSONArray jsMetas = client.getTaskList(gid); for (int j = 0; j < jsMetas.length(); j++) { object = (JSONObject) jsMetas.getJSONObject(j); MetaData metaData = new MetaData(); metaData.setContentByRemoteJSON(object); if (metaData.isWorthSaving()) { mMetaList.addChildTask(metaData); if (metaData.getGid() != null) { mMetaHashMap.put(metaData.getRelatedGid(), metaData); } } } } } // create meta list if not existed if (mMetaList == null) { mMetaList = new TaskList(); mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META); GTaskClient.getInstance().createTaskList(mMetaList); } // init task list for (int i = 0; i < jsTaskLists.length(); i++) { JSONObject object = jsTaskLists.getJSONObject(i); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { TaskList tasklist = new TaskList(); tasklist.setContentByRemoteJSON(object); mGTaskListHashMap.put(gid, tasklist); mGTaskHashMap.put(gid, tasklist); // load tasks JSONArray jsTasks = client.getTaskList(gid); for (int j = 0; j < jsTasks.length(); j++) { object = (JSONObject) jsTasks.getJSONObject(j); gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); Task task = new Task(); task.setContentByRemoteJSON(object); if (task.isWorthSaving()) { task.setMetaInfo(mMetaHashMap.get(gid)); tasklist.addChildTask(task); mGTaskHashMap.put(gid, task); } } } } } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); throw new ActionFailureException("initGTaskList: handing JSONObject failed"); } }
From source file:cn.code.notes.gtask.remote.GTaskManager.java
private void addLocalNode(Node node) throws NetworkFailureException { if (mCancelled) { return;/* w w w .j av a2 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:es.prodevelop.gvsig.mini.json.GeoJSONParser.java
private FeatureCollection decodeFeatureCollection(JSONObject object) throws JSONException { FeatureCollection fCollection = null; JSONArray array = object.getJSONArray("features"); if (array != null) { fCollection = new FeatureCollection(); for (int i = 0; i < array.length(); i++) { JSONObject o = array.getJSONObject(i); if (o.get("type").equals("Feature")) { Feature f = this.decodeFeature(o); fCollection.addFeature(f); }//from w ww . j a va 2s . co m } } return fCollection; }
From source file:es.prodevelop.gvsig.mini.json.GeoJSONParser.java
private IGeometry decodeGeometry(JSONObject object) throws JSONException { IGeometry geom = null;//from w w w . j av a2s .c o m LineString[] lineStrings; if (object.get("type").equals("MultiLineString")) { JSONArray coordinates = object.getJSONArray("coordinates"); int size = coordinates.length(); lineStrings = new LineString[size]; LineString l; for (int i = 0; i < size; i++) { JSONArray lineStrCoord = coordinates.getJSONArray(i); double[][] coords = this.decodeLineStringCoords(lineStrCoord); l = new LineString(coords[0], coords[1]); lineStrings[i] = l; } geom = new MultiLineString(lineStrings); } else if (object.get("type").equals("LineString")) { JSONArray coordinates = object.getJSONArray("coordinates"); double[][] coords = this.decodeLineStringCoords(coordinates); geom = new LineString(coords[0], coords[1]); } else if (object.get("type").equals("Point")) { JSONArray coordinates = object.getJSONArray("coordinates"); geom = new Point(coordinates.getDouble(0), coordinates.getDouble(1)); } else if (object.get("type").equals("Polygon")) { JSONArray coordinates = object.getJSONArray("coordinates"); double[][] coords = this.decodeLineStringCoords(coordinates); geom = new Polygon(coords[0], coords[1]); } return geom; }