List of usage examples for org.json JSONArray getJSONObject
public JSONObject getJSONObject(int index) throws JSONException
From source file:au.com.borner.salesforce.client.rest.domain.AbstractJSONObject.java
@SuppressWarnings("unchecked") protected <T extends AbstractJSONObject> List<T> getChildEntities(String name, Class<T> resultClass) { try {/*from ww w . j av a 2 s. c o m*/ Constructor<T> constructor = resultClass.getConstructor(String.class); JSONArray children = getJSONArray(name); List<T> result = new ArrayList<T>(children.length()); for (int i = 0; i < children.length(); i++) { JSONObject jsonObject = children.getJSONObject(i); T instance = constructor.newInstance(jsonObject.toString()); // is there any way to avoid double serialisation? result.add(instance); } return result; } catch (Exception e) { throw new RuntimeException("Error parsing child elements", e); } }
From source file:account.management.controller.inventory.PurchaseReportController.java
@FXML private void onShowReportButtonClick(ActionEvent event) { this.show.setDisable(true); try {//from w ww .j a va 2 s.c om String id = String.valueOf(this.item.getSelectionModel().getSelectedItem().getId()); String start_date = "1980-01-01", end_date = "2050-12-31"; start_date = new SimpleDateFormat("yyyy-MM-dd") .format(new SimpleDateFormat("yyyy-MM-dd").parse(this.start.getValue().toString())); end_date = new SimpleDateFormat("yyyy-MM-dd") .format(new SimpleDateFormat("yyyy-MM-dd").parse(this.end.getValue().toString())); HttpResponse<JsonNode> res = Unirest.get(MetaData.baseUrl + "report/ledger/purchase") .queryString("id", id).queryString("start", start_date).queryString("end", end_date).asJson(); JSONArray array = res.getBody().getArray(); System.out.println(array); Vector v = new Vector(); HashMap params = new HashMap(); params.put("date", "From " + new SimpleDateFormat("dd-MM-yyyy") .format(new SimpleDateFormat("yyyy-MM-dd").parse(start_date)) + " To " + new SimpleDateFormat("dd-MM-yyyy") .format(new SimpleDateFormat("yyyy-MM-dd").parse(end_date))); params.put("item_name", "Purchase report of " + this.item.getSelectionModel().getSelectedItem().getName()); for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); String date = obj.getString("date"); String quantity = obj.get("quantity").toString(); String rate = obj.get("rate").toString(); v.add(new SellPurchaseLedger(date, quantity, rate)); } Report report = new Report(); report.getReport("src\\report\\SellPurchaseLedger.jrxml", new JRBeanCollectionDataSource(v), params, "Purchase Report"); this.show.setDisable(false); } catch (Exception e) { System.out.println("Exception in show report button click"); Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText(null); alert.setContentText("Sorry!! there is an error. Please try again."); alert.setGraphic(new ImageView(new Image("resources/error.jpg"))); alert.showAndWait(); } }
From source file:com.jvoid.quote.controller.JVoidQuoteController.java
public ProductsMaster getJVoidProduct(int productId) { RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); JSONObject jsonObj = new JSONObject(); try {//ww w. j av a 2 s . c om jsonObj.put("id", productId); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("param jsonObj=>" + jsonObj.toString()); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(PRODUCT_SERVER_URI + URIConstants.GET_PRODUCT).queryParam("params", jsonObj); HttpEntity<?> entity = new HttpEntity<>(headers); HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity, String.class); System.out.println("returnString=>" + returnString); JSONObject returnJsonObj = null; try { returnJsonObj = new JSONObject(returnString.getBody()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } JSONArray productsArr = null; ProductsMaster productsMaster = null; try { productsArr = returnJsonObj.getJSONArray("products"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } productsMaster = new ProductsMaster(); try { ObjectMapper mapper = new ObjectMapper(); try { productsMaster = mapper.readValue(productsArr.getJSONObject(0).toString(), ProductsMaster.class); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return productsMaster; }
From source file:com.clevertrail.mobile.findtrail.Activity_FindTrail_ByName.java
private int submitSearch() { JSONArray jsonArray = null; HttpURLConnection urlConnection = null; try {/* w w w.jav a 2 s. c o m*/ //api call to find trails by name String requestURL = "http://clevertrail.com/ajax/handleGetArticles.php"; String sSearch = mActivity.sSearchText; sSearch = sSearch.replace(" ", "%20"); sSearch = sSearch.replace("'", "\'"); requestURL = requestURL.concat("?name=").concat(sSearch); URL url = new URL(requestURL); urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); BufferedReader r = new BufferedReader(new InputStreamReader(in)); String line; //did we get a match from clevertrail.com? if ((line = r.readLine()) != null) { jsonArray = new JSONArray(line); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return R.string.error_contactingclevertrail; } catch (IOException e) { // TODO Auto-generated catch block // could not connect to clevertrail.com e.printStackTrace(); return R.string.error_contactingclevertrail; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); return R.string.error_corrupttrailinfo; } finally { if (urlConnection != null) urlConnection.disconnect(); } //clear the static object that holds the trails Object_TrailList.clearTrails(); if (jsonArray != null && jsonArray.length() > 0) { int len = jsonArray.length(); try { //add each trail to the array of trails for (int i = 0; i < len && i < 20; ++i) { JSONObject trail = jsonArray.getJSONObject(i); Object_TrailList.addTrailWithJSON(trail); } } catch (JSONException e) { return R.string.error_corrupttrailinfo; } } //prepare the extras before starting the trail list activity int icon = R.drawable.ic_viewtrailtab_details_unselected; Intent i = new Intent(mActivity, Activity_ListTrails.class); i.putExtra("icon", icon); i.putExtra("title", mActivity.getString(R.string.title_foundtrails)); mActivity.startActivity(i); return 0; }
From source file:github.popeen.dsub.util.SongDBHandler.java
public void importData(JSONArray array) { SQLiteDatabase db = this.getReadableDatabase(); try {/*w w w.j a v a2 s .c om*/ for (int i = 0; i < array.length(); i++) { JSONObject row = array.getJSONObject(i); ContentValues values = new ContentValues(); values.put(SONGS_ID, row.getInt("SONGS_ID")); values.put(SONGS_SERVER_KEY, row.getInt("SONGS_SERVER_KEY")); values.put(SONGS_SERVER_ID, row.getString("SONGS_SERVER_ID")); values.put(SONGS_COMPLETE_PATH, row.getString("SONGS_COMPLETE_PATH")); values.put(SONGS_LAST_PLAYED, row.getInt("SONGS_LAST_PLAYED")); values.put(SONGS_LAST_COMPLETED, row.getInt("SONGS_LAST_COMPLETED")); db.insertWithOnConflict(TABLE_SONGS, null, values, SQLiteDatabase.CONFLICT_REPLACE); } } catch (Exception e) { } }
From source file:com.daskiworks.ghwatch.backend.NotificationStreamParser.java
public static NotificationStream parseNotificationStream(JSONArray json) throws InvalidObjectException { NotificationStream ret = new NotificationStream(); try {/* w w w. ja va 2s.c om*/ for (int i = 0; i < json.length(); i++) { JSONObject notification = json.getJSONObject(i); JSONObject subject = notification.getJSONObject("subject"); JSONObject repository = notification.getJSONObject("repository"); String updatedAtStr = Utils.trimToNull(notification.getString("updated_at")); Date updatedAt = null; try { if (updatedAtStr != null) { if (updatedAtStr.endsWith("Z")) updatedAtStr = updatedAtStr.replace("Z", "GMT"); updatedAt = df.parse(updatedAtStr); } } catch (ParseException e) { Log.w(TAG, "Invalid date format for value: " + updatedAtStr); } ret.addNotification(new Notification(notification.getLong("id"), notification.getString("url"), subject.getString("title"), subject.getString("type"), subject.getString("url"), subject.getString("latest_comment_url"), repository.getString("full_name"), repository.getJSONObject("owner").getString("avatar_url"), updatedAt, notification.getString("reason"))); } } catch (Exception e) { throw new InvalidObjectException("JSON message is invalid: " + e.getMessage()); } return ret; }
From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java
public static RadioSong GetCurrentSongInformation(Context context, RadioRedditApplication application) { RadioSong radiosong = new RadioSong(); radiosong.ErrorMessage = ""; try {/*from ww w .ja v a 2 s . co m*/ String status_url = context.getString(R.string.radio_reddit_base_url) + application.CurrentStream.Status + context.getString(R.string.radio_reddit_status); String outputStatus = ""; boolean errorGettingStatus = false; try { outputStatus = HTTPUtil.get(context, status_url); } catch (Exception ex) { ex.printStackTrace(); errorGettingStatus = true; // For now, not used. It is acceptable to error out and not alert the user // radiosong.ErrorMessage = context.getString(R.string.error_RadioRedditServerIsDownNotification); } if (!errorGettingStatus && outputStatus.length() > 0) { JSONTokener status_tokener = new JSONTokener(outputStatus); JSONObject status_json = new JSONObject(status_tokener); radiosong.Playlist = status_json.getString("playlist"); JSONObject songs = status_json.getJSONObject("songs"); JSONArray songs_array = songs.getJSONArray("song"); // get the first song in the array JSONObject song = songs_array.getJSONObject(0); radiosong.ID = song.getInt("id"); radiosong.Title = song.getString("title"); radiosong.Artist = song.getString("artist"); radiosong.Redditor = song.getString("redditor"); radiosong.Genre = song.getString("genre"); radiosong.CumulativeScore = song.getString("score"); if (radiosong.CumulativeScore.equals("{}")) radiosong.CumulativeScore = null; radiosong.Reddit_title = song.getString("reddit_title"); radiosong.Reddit_url = song.getString("reddit_url"); if (song.has("preview_url")) radiosong.Preview_url = song.getString("preview_url"); if (song.has("download_url")) radiosong.Download_url = song.getString("download_url"); if (song.has("bandcamp_link")) radiosong.Bandcamp_link = song.getString("bandcamp_link"); if (song.has("bandcamp_art")) radiosong.Bandcamp_art = song.getString("bandcamp_art"); if (song.has("itunes_link")) radiosong.Itunes_link = song.getString("itunes_link"); if (song.has("itunes_art")) radiosong.Itunes_art = song.getString("itunes_art"); if (song.has("itunes_price")) radiosong.Itunes_price = song.getString("itunes_price"); // get vote score String reddit_info_url = context.getString(R.string.reddit_link_by) + URLEncoder.encode(radiosong.Reddit_url); String outputRedditInfo = ""; boolean errorGettingRedditInfo = false; try { outputRedditInfo = HTTPUtil.get(context, reddit_info_url); } catch (Exception ex) { ex.printStackTrace(); errorGettingRedditInfo = true; // For now, not used. It is acceptable to error out and not alert the user // radiosong.ErrorMessage = "Unable to connect to reddit";//context.getString(R.string.error_RadioRedditServerIsDownNotification); } if (!errorGettingRedditInfo && outputRedditInfo.length() > 0) { // Log.e("radio_reddit_test", "Length: " + outputRedditInfo.length()); // Log.e("radio_reddit_test", "Value: " + outputRedditInfo); // TODO: sometimes the value contains "error: 404", need to check for that. (We can probably safely ignore this for now) JSONTokener reddit_info_tokener = new JSONTokener(outputRedditInfo); JSONObject reddit_info_json = new JSONObject(reddit_info_tokener); JSONObject data = reddit_info_json.getJSONObject("data"); // default value of score String score = context.getString(R.string.vote_to_submit_song); String likes = "null"; String name = ""; JSONArray children_array = data.getJSONArray("children"); // Song hasn't been submitted yet if (children_array.length() > 0) { JSONObject children = children_array.getJSONObject(0); JSONObject children_data = children.getJSONObject("data"); score = children_data.getString("score"); likes = children_data.getString("likes"); name = children_data.getString("name"); } radiosong.Score = score; radiosong.Likes = likes; radiosong.Name = name; } else { radiosong.Score = "?"; radiosong.Likes = "null"; radiosong.Name = ""; } return radiosong; } return null; } catch (Exception ex) { // We fail to get the current song information... CustomExceptionHandler ceh = new CustomExceptionHandler(context); ceh.sendEmail(ex); ex.printStackTrace(); radiosong.ErrorMessage = ex.toString(); return radiosong; } }
From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java
public static RadioEpisode GetCurrentEpisodeInformation(Context context, RadioRedditApplication application) { RadioEpisode radioepisode = new RadioEpisode(); radioepisode.ErrorMessage = ""; try {/*from www . j a v a 2 s . c om*/ String status_url = context.getString(R.string.radio_reddit_base_url) + application.CurrentStream.Status + context.getString(R.string.radio_reddit_status); String outputStatus = ""; boolean errorGettingStatus = false; try { outputStatus = HTTPUtil.get(context, status_url); } catch (Exception ex) { ex.printStackTrace(); errorGettingStatus = true; // For now, not used. It is acceptable to error out and not alert the user // radiosong.ErrorMessage = context.getString(R.string.error_RadioRedditServerIsDownNotification); } if (!errorGettingStatus && outputStatus.length() > 0) { JSONTokener status_tokener = new JSONTokener(outputStatus); JSONObject status_json = new JSONObject(status_tokener); radioepisode.Playlist = status_json.getString("playlist"); JSONObject episodes = status_json.getJSONObject("episodes"); JSONArray episodes_array = episodes.getJSONArray("episode"); // get the first episode in the array JSONObject song = episodes_array.getJSONObject(0); radioepisode.ID = song.getInt("id"); radioepisode.EpisodeTitle = song.getString("episode_title"); radioepisode.EpisodeDescription = song.getString("episode_description"); radioepisode.EpisodeKeywords = song.getString("episode_keywords"); radioepisode.ShowTitle = song.getString("show_title"); radioepisode.ShowHosts = song.getString("show_hosts").replaceAll(",", ", "); radioepisode.ShowRedditors = song.getString("show_redditors").replaceAll(",", ", "); radioepisode.ShowGenre = song.getString("show_genre"); radioepisode.ShowFeed = song.getString("show_feed"); radioepisode.Reddit_title = song.getString("reddit_title"); radioepisode.Reddit_url = song.getString("reddit_url"); if (song.has("preview_url")) radioepisode.Preview_url = song.getString("preview_url"); if (song.has("download_url")) radioepisode.Download_url = song.getString("download_url"); // get vote score String reddit_info_url = context.getString(R.string.reddit_link_by) + URLEncoder.encode(radioepisode.Reddit_url); String outputRedditInfo = ""; boolean errorGettingRedditInfo = false; try { outputRedditInfo = HTTPUtil.get(context, reddit_info_url); } catch (Exception ex) { ex.printStackTrace(); errorGettingRedditInfo = true; // For now, not used. It is acceptable to error out and not alert the user // radiosong.ErrorMessage = "Unable to connect to reddit";//context.getString(R.string.error_RadioRedditServerIsDownNotification); } if (!errorGettingRedditInfo && outputRedditInfo.length() > 0) { // Log.e("radio_reddit_test", "Length: " + outputRedditInfo.length()); // Log.e("radio_reddit_test", "Value: " + outputRedditInfo); // TODO: sometimes the value contains "error: 404", need to check for that (We can probably safely ignore this for now) JSONTokener reddit_info_tokener = new JSONTokener(outputRedditInfo); JSONObject reddit_info_json = new JSONObject(reddit_info_tokener); JSONObject data = reddit_info_json.getJSONObject("data"); // default value of score String score = context.getString(R.string.vote_to_submit_song); String likes = "null"; String name = ""; JSONArray children_array = data.getJSONArray("children"); // Episode hasn't been submitted yet if (children_array.length() > 0) { JSONObject children = children_array.getJSONObject(0); JSONObject children_data = children.getJSONObject("data"); score = children_data.getString("score"); likes = children_data.getString("likes"); name = children_data.getString("name"); } radioepisode.Score = score; radioepisode.Likes = likes; radioepisode.Name = name; } else { radioepisode.Score = "?"; radioepisode.Likes = "null"; radioepisode.Name = ""; } return radioepisode; } return null; } catch (Exception ex) { // We fail to get the current song information... CustomExceptionHandler ceh = new CustomExceptionHandler(context); ceh.sendEmail(ex); ex.printStackTrace(); radioepisode.ErrorMessage = ex.toString(); return radioepisode; } }
From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java
public static List<RadioSong> GetTopChartsByType(Context context, RadioRedditApplication application, String type) {//www.j av a 2 s. co m List<RadioSong> radiosongs = new ArrayList<RadioSong>(); try { String chart_url = ""; if (type.equals("all")) chart_url = context.getString(R.string.radio_reddit_charts_all); else if (type.equals("month")) chart_url = context.getString(R.string.radio_reddit_charts_month); else if (type.equals("week")) chart_url = context.getString(R.string.radio_reddit_charts_week); else if (type.equals("day")) chart_url = context.getString(R.string.radio_reddit_charts_day); // TODO: might could merge this code with GetCurrentSongInformation String outputStatus = ""; boolean errorGettingStatus = false; try { outputStatus = HTTPUtil.get(context, chart_url); } catch (Exception ex) { ex.printStackTrace(); errorGettingStatus = true; // For now, not used. It is acceptable to error out and not alert the user // radiosong.ErrorMessage = context.getString(R.string.error_RadioRedditServerIsDownNotification); } if (!errorGettingStatus && outputStatus.length() > 0) { JSONTokener status_tokener = new JSONTokener(outputStatus); JSONObject status_json = new JSONObject(status_tokener); JSONObject songs = status_json.getJSONObject("songs"); JSONArray songs_array = songs.getJSONArray("song"); // get the first song in the array for (int i = 0; i < songs_array.length(); i++) { RadioSong radiosong = new RadioSong(); radiosong.ErrorMessage = ""; JSONObject song = songs_array.getJSONObject(i); //radiosong.ID = song.getInt("id"); radiosong.Title = song.getString("title"); radiosong.Artist = song.getString("artist"); radiosong.Redditor = song.getString("redditor"); radiosong.Genre = song.getString("genre"); //radiosong.CumulativeScore = song.getString("score"); //if(radiosong.CumulativeScore.equals("{}")) // radiosong.CumulativeScore = null; radiosong.Reddit_title = song.getString("reddit_title"); radiosong.Reddit_url = song.getString("reddit_url"); if (song.has("preview_url")) radiosong.Preview_url = song.getString("preview_url"); if (song.has("download_url")) radiosong.Download_url = song.getString("download_url"); if (song.has("bandcamp_link")) radiosong.Bandcamp_link = song.getString("bandcamp_link"); if (song.has("bandcamp_art")) radiosong.Bandcamp_art = song.getString("bandcamp_art"); if (song.has("itunes_link")) radiosong.Itunes_link = song.getString("itunes_link"); if (song.has("itunes_art")) radiosong.Itunes_art = song.getString("itunes_art"); if (song.has("itunes_price")) radiosong.Itunes_price = song.getString("itunes_price"); radiosongs.add(radiosong); } } } catch (Exception ex) { // We fail to get the current song information... CustomExceptionHandler ceh = new CustomExceptionHandler(context); ceh.sendEmail(ex); ex.printStackTrace(); // TODO: return error message?? Might need to wrap List<RadioSong> in an object that has an ErrorMessage data member //radiosong.ErrorMessage = ex.toString(); //return radiosong; } return radiosongs; }
From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java
public static RadioSong GetSongVoteScore(Context context, RadioRedditApplication application, RadioSong radiosong) {/*from www .j ava 2 s.co m*/ try { // get vote score String reddit_info_url = context.getString(R.string.reddit_link_by) + URLEncoder.encode(radiosong.Reddit_url); String outputRedditInfo = ""; boolean errorGettingRedditInfo = false; try { outputRedditInfo = HTTPUtil.get(context, reddit_info_url); } catch (Exception ex) { ex.printStackTrace(); errorGettingRedditInfo = true; // For now, not used. It is acceptable to error out and not alert the user // radiosong.ErrorMessage = "Unable to connect to reddit";//context.getString(R.string.error_RadioRedditServerIsDownNotification); } if (!errorGettingRedditInfo && outputRedditInfo.length() > 0) { // Log.e("radio_reddit_test", "Length: " + outputRedditInfo.length()); // Log.e("radio_reddit_test", "Value: " + outputRedditInfo); // TODO: sometimes the value contains "error: 404", need to check for that. (We can probably safely ignore this for now) JSONTokener reddit_info_tokener = new JSONTokener(outputRedditInfo); JSONObject reddit_info_json = new JSONObject(reddit_info_tokener); JSONObject data = reddit_info_json.getJSONObject("data"); // default value of score String score = context.getString(R.string.vote_to_submit_song); String likes = "null"; String name = ""; JSONArray children_array = data.getJSONArray("children"); // Song hasn't been submitted yet if (children_array.length() > 0) { JSONObject children = children_array.getJSONObject(0); JSONObject children_data = children.getJSONObject("data"); score = children_data.getString("score"); likes = children_data.getString("likes"); name = children_data.getString("name"); } radiosong.Score = score; radiosong.Likes = likes; radiosong.Name = name; } else { radiosong.Score = "?"; radiosong.Likes = "null"; radiosong.Name = ""; } } catch (Exception ex) { // We fail to get the vote information... CustomExceptionHandler ceh = new CustomExceptionHandler(context); ceh.sendEmail(ex); ex.printStackTrace(); // return error message?? radiosong.ErrorMessage = context.getString(R.string.error_GettingVoteInformation); //return radiosong; } return radiosong; }