List of usage examples for org.json.simple JSONArray get
public E get(int index)
From source file:iracing.webapi.TimeTrialResultStandingsParser.java
public static TimeTrialResultStandings parse(String json) { TimeTrialResultStandings output = null; JSONParser parser = new JSONParser(); try {// w w w .j ava2 s.c o m JSONObject root = (JSONObject) parser.parse(json); Object o = root.get("d"); if (o instanceof JSONObject) { JSONObject d = (JSONObject) o; output = new TimeTrialResultStandings(); String s = (String) d.get("3"); output.setApiUserRow(Integer.parseInt(s)); output.setTotalRecords(getInt(d, "17")); JSONArray arrayRoot = (JSONArray) d.get("r"); List<TimeTrialResultStanding> standings = new ArrayList<TimeTrialResultStanding>(); for (int i = 0; i < arrayRoot.size(); i++) { JSONObject r = (JSONObject) arrayRoot.get(i); TimeTrialResultStanding standing = new TimeTrialResultStanding(); o = r.get("1"); if (o instanceof Double) { standing.setPoints((Double) o); } else if (o instanceof Long) { standing.setPoints(Double.parseDouble(String.valueOf(o))); } standing.setLicenseSubLevel(getString(r, "2")); standing.setMaxLicenseLevel(getInt(r, "4")); standing.setRank(getInt(r, "5")); standing.setDivision(getInt(r, "7")); standing.setDriverName(getString(r, "8", true)); standing.setDriverCustomerId(getLong(r, "10")); standing.setTotalStarts(getInt(r, "12")); standing.setBestTimeFormatted(getString(r, "13", true)); o = r.get("14"); if (o instanceof Long) { standing.setBestTime((Long) o); } else { // drivers setting no time will have an empty string ("14":"") standing.setBestTime(-1L); } standing.setClubId(getInt(r, "15")); standing.setPosition(getLong(r, "18")); standings.add(standing); } output.setStandings(standings); } } catch (ParseException ex) { Logger.getLogger(TimeTrialResultStandingsParser.class.getName()).log(Level.SEVERE, null, ex); } return output; }
From source file:it.cnr.isti.thematrix.scripting.sys.DatasetSchema.java
/** * Convert the argument JSON string into a DatasetSchema * @param jsonContent /*from w w w .j a va 2 s.c om*/ * @return a DatasetSchema */ public static DatasetSchema fromJSON(String jsonContent) { Object obj = JSONValue.parse(jsonContent); JSONArray array = (JSONArray) obj; String schemaName = (String) array.get(0); DatasetSchema ds = new DatasetSchema(schemaName); for (int i = 1; i < array.size(); i++) { JSONObject o = (JSONObject) array.get(i); String name = (String) o.get("name"); DataType type = DataType.valueOf((String) o.get("type")); ds.put(new Symbol<Integer>(name, null, type)); } return ds; }
From source file:iracing.webapi.WorldRecordsParser.java
static WorldRecords parse(String json, boolean includeApiUserRow) { JSONParser parser = new JSONParser(); WorldRecords output = null;/*from www .j a v a 2 s. c o m*/ try { JSONObject root = (JSONObject) parser.parse(json); output = new WorldRecords(); JSONObject root2 = (JSONObject) root.get("d"); output.setApiUserRow(getLong(root2, "22")); output.setTotalResults(getLong(root2, "32")); JSONArray rootArray = (JSONArray) root2.get("r"); List<WorldRecord> recordList = new ArrayList<WorldRecord>(); for (int i = 0; i < rootArray.size(); i++) { JSONObject r = (JSONObject) rootArray.get(i); long recordNumber = getLong(r, "36"); if (!includeApiUserRow && recordNumber == 0) continue; WorldRecord wr = new WorldRecord(); wr.setClubName(getString(r, "1", true)); wr.setCountryCode(getString(r, "2")); wr.setLicenseSubLevel(getInt(r, "3")); wr.setIrating(getInt(r, "4")); wr.setTimeTrialSubSessionId(getLong(r, "5")); wr.setQualify(getString(r, "6", true)); IracingCustomer driver = new IracingCustomer(); driver.setId(getLong(r, "26")); driver.setName(getString(r, "7", true)); wr.setDriver(driver); long l = getLong(r, "8"); if (l > 0) wr.setPracticeStartTime(new Date(l)); wr.setSeasonQuarter(getInt(r, "9")); wr.setClubId(getInt(r, "10")); wr.setRace(getString(r, "11", true)); wr.setLicenseSubLevelText(getString(r, "13", true)); wr.setSeasonYear(getInt(r, "14")); wr.setTimeTrialRating(getInt(r, "15")); wr.setLicenseGroupId(getInt(r, "16")); wr.setRaceSubSessionId(getLong(r, "17")); l = getLong(r, "18"); if (l > 0) wr.setTimeTrialStartTime(new Date(l)); wr.setQualifyingSubSessionId(getLong(r, "19")); wr.setLicenseLevelId(getInt(r, "20")); wr.setTrackId(getInt(r, "21")); wr.setTimeTrial(getString(r, "23", true)); wr.setCarId(getInt(r, "28")); wr.setCategoryId(getInt(r, "29")); wr.setRegionName(getString(r, "30", true)); wr.setPracticeSubSessionId(getLong(r, "31")); l = getLong(r, "33"); if (l > 0) wr.setRaceStartTime(new Date(l)); wr.setPractice(getString(r, "34", true)); l = getLong(r, "35"); wr.setRecordNumber(recordNumber); if (l > 0) wr.setQualifyingStartTime(new Date(l)); wr.setCategoryName(getString(r, "37")); recordList.add(wr); } output.setRecords(recordList); } catch (ParseException ex) { Logger.getLogger(WorldRecordsParser.class.getName()).log(Level.SEVERE, null, ex); } return output; }
From source file:iracing.webapi.SessionResultSummaryParser.java
public static void parse(String json, ItemHandler handler) { if (handler != null) { JSONParser parser = new JSONParser(); try {/*from w ww .j a v a 2 s . c o m*/ JSONObject root = (JSONObject) parser.parse(json); //"1":"champpointssort","2":"raw_start_time","3":"bestlaptime","4":"start_time" //"5":"groupname","6":"helm_pattern","7":"season_year","8":"clubpoints","9":"subsession_bestlaptime" //"10":"evttype","11":"winnerlicenselevel","12":"strengthoffield","13":"dropracepoints","14":"finishedat" //"15":"trackid","16":"winnercustid","17":"custid","18":"winnerdisplayname","19":"sessionid" //"20":"clubpointssort","21":"rn","22":"seasonid","23":"carclassid","24":"helm_licenselevel" //"25":"starting_position","26":"officialsession","27":"displayname","28":"helm_color1","29":"season_quarter" //"30":"helm_color2","31":"helm_color3","32":"seriesid","33":"bestquallaptime","34":"licensegroup" //"35":"incidents","36":"champpoints","37":"race_week_num","38":"start_date","39":"winnerhelmcolor1" //"40":"winnerhelmcolor2","41":"winnerhelmcolor3","42":"carid","43":"subsessionid","44":"catid" //"45":"winnerhelmpattern","46":"rowcount","47":"finishing_position" // Only continue if 'd' is an JSONObject, not if it's an JSONArray (as is returned when invalid parameters are passed) // {"m":{},"d":[]} Object o = root.get("d"); if (o instanceof JSONObject) { JSONObject d = (JSONObject) o; long totalRecords = getLong(d, "46"); JSONArray r = (JSONArray) d.get("r"); for (int i = 0; i < r.size(); i++) { JSONObject rItem = (JSONObject) r.get(i); SessionResultSummary summary = new SessionResultSummary(); //{"1":-1,"2":1339938000000,"3":"47.636","4":"01%3A00pm","5":"Rookie","6":48,"7":2012,"8":0,"9":"47.597", //"10":5,"11":18,"12":1390,"13":"","14":1339940125000,"15":116,"16":72331,"17":29462,"18":"Robby+Singleton","19":25672697, //"20":0,"21":1,"22":686,"23":19,"24":19,"25":6,"26":0,"27":"Christian+Aylward","28":111,"29":2, //"30":255,"31":127,"32":116,"33":"","34":1,"35":4,"36":"","37":6,"38":"2012.06.17","39":22, //"40":67,"41":39,"42":22,"43":5854525,"44":1,"45":56,"47":3} summary.setStartTime(new Date(getLong(rItem, "2"))); summary.setBestLapTime(getString(rItem, "3")); summary.setGroupName(getString(rItem, "5")); summary.setSeasonYear(getInt(rItem, "7")); String s = getString(rItem, "8"); if (!"".equals(s)) summary.setClubPoints(Integer.parseInt(s)); summary.setSessionBestLapTime(getString(rItem, "9")); summary.setEventType(getInt(rItem, "10")); summary.setWinnerLicenseLevel(getInt(rItem, "11")); summary.setStrengthOfField(getInt(rItem, "12")); s = getString(rItem, "13"); if (!"".equals(s)) summary.setDropRacePoints(Integer.parseInt(s)); summary.setFinishDate(new Date(getLong(rItem, "14"))); summary.setTrackId(getInt(rItem, "15")); summary.setWinnerCustomerId(getLong(rItem, "16")); summary.setCustomerId(getLong(rItem, "17")); summary.setWinnerDisplayName(getString(rItem, "18", true)); summary.setSessionId(getLong(rItem, "19")); summary.setSeasonId(getInt(rItem, "22")); summary.setCarClassId(getInt(rItem, "23")); summary.setStartingPosition(getInt(rItem, "25")); summary.setOfficialSession((getInt(rItem, "26")) == 1); summary.setDisplayName(getString(rItem, "27", true)); summary.setSeasonQuarter(getInt(rItem, "29")); summary.setSeriesId(getInt(rItem, "32")); summary.setBestQualifyingLapTime(getString(rItem, "33")); summary.setLicenseGroup(getInt(rItem, "34")); summary.setIncidents(getInt(rItem, "35")); Object a = rItem.get("36"); if (a instanceof Long) { summary.setChampionshipPoints(((Long) a).intValue()); } // s = (String)rItem.get("36"); // if (!"".equals(s)) summary.setChampionshipPoints(Integer.parseInt(s)); summary.setRaceWeek(getInt(rItem, "37")); summary.setStartDate(getString(rItem, "38")); summary.setCarId(getInt(rItem, "42")); summary.setSubSessionId(getLong(rItem, "43")); summary.setCategoryId(getInt(rItem, "44")); summary.setFinishingPosition(getInt(rItem, "47")); if (!handler.onSessionResultSummaryParsed(summary)) break; } } } catch (Exception ex) { Logger.getLogger(SessionResultSummaryParser.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:Bing.java
/** * * @param query - query to use for the search * @return - a json array of results. each contains a title, description, url, * and some other metadata that can be easily extracted since its in json format *///from www. j a v a 2s.c o m public static JSONArray search(String query) { try { query = "'" + query + "'"; String encodedQuery = URLEncoder.encode(query, "UTF-8"); System.out.println(encodedQuery); // URL url = new URL("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query=%27car%27"); // URL url = new URL("http://csb.stanford.edu/class/public/pages/sykes_webdesign/05_simple.html"); String webPage = "https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query=" + encodedQuery + "&$format=JSON"; String name = "6604d12c-3e89-4859-8013-3132f78c1595"; String password = "cefgNRl3OL4PrJJvssxkqLw0VKfYNCgyTe8wNXotUmQ"; String authString = name + ":" + password; System.out.println("auth string: " + authString); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); System.out.println("Base64 encoded auth string: " + authStringEnc); URL url = new URL(webPage); URLConnection urlConnection = url.openConnection(); urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine).append("\n"); } in.close(); JSONParser parser = new JSONParser(); JSONArray arr = (JSONArray) ((JSONObject) ((JSONObject) parser.parse(response.toString())).get("d")) .get("results"); JSONObject obj = (JSONObject) arr.get(0); JSONArray out = (JSONArray) obj.get("Web"); return out; // } catch (MalformedURLException ex) { Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException ex) { Logger.getLogger(Bing.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:mp3downloader.ZingSearch.java
private static ArrayList<Song> readSongsFromContent(String content) throws ParseException { ArrayList<Song> songs = new ArrayList<Song>(); JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject) parser.parse(content); JSONArray items = (JSONArray) obj.get("Data"); for (int i = 0; i < items.size(); i++) { JSONObject item = (JSONObject) items.get(i); String id = (String) item.get("ID"); String title = (String) item.get("Title"); String performer = (String) item.get("Artist"); String thumbnail = (String) item.get("ArtistAvatar"); String source = ""; if (item.get("LinkDownload320") != null) { source = (String) item.get("LinkDownload320"); } else if (item.get("LinkDownload128") != null) { source = (String) item.get("LinkDownload128"); }/* ww w . j av a 2 s . c om*/ String type = "mp3"; Song song = new Song(id, title, performer, source, thumbnail, type); songs.add(song); } return songs; }
From source file:iracing.webapi.DriverStatsParser.java
static DriverStats parse(String json, boolean includeApiUserTopRow) { JSONParser parser = new JSONParser(); DriverStats output = null;//from w w w .j a v a 2s. com try { JSONObject root = (JSONObject) parser.parse(json); JSONObject root2 = (JSONObject) root.get("d"); output = new DriverStats(); output.setApiUserRow(getLong(root2, "24")); output.setTotalRecords(getLong(root2, "33")); JSONArray arrayRoot = (JSONArray) root2.get("r"); List<DriverStat> statList = new ArrayList<DriverStat>(); for (int i = 0; i < arrayRoot.size(); i++) { JSONObject r = (JSONObject) arrayRoot.get(i); long recordNumber = getLong(r, "37"); if (!includeApiUserTopRow && recordNumber == 0) continue; DriverStat ds = new DriverStat(); ds.setClubName(getString(r, "1", true)); ds.setCountryCode(getString(r, "2", true)); ds.setLicenseSubLevel(getInt(r, "3")); ds.setIratingRank(getLong(r, "4")); ds.setAverageFinishingPosition(getInt(r, "5")); ds.setIrating(getInt(r, "6")); ds.setLicenseGroupName(getString(r, "7", true)); IracingCustomer driver = new IracingCustomer(); driver.setName(getString(r, "8", true)); driver.setId(getLong(r, "29")); ds.setDriver(driver); ds.setTimeTrialRatingRank(getLong(r, "9")); ds.setAverageIncidentsPerRace(getDouble(r, "10")); ds.setTotalTop25PercentFinishes(getLong(r, "11")); ds.setClubId(getInt(r, "12")); ds.setTotalStarts(getLong(r, "13")); ds.setLicenseClassRank(getLong(r, "15")); ds.setTotalLapsLed(getLong(r, "16")); ds.setTotalWins(getLong(r, "17")); ds.setTotalClubPoints(getLong(r, "18")); ds.setTimeTrialRating(getInt(r, "19")); ds.setLicenseGroupId(getInt(r, "20")); ds.setLicenseLevelId(getInt(r, "21")); ds.setTotalChampionshipPoints(getLong(r, "22")); ds.setLicenseGroupLetter(getString(r, "23", true)); ds.setAverageFieldSize(getInt(r, "25")); ds.setRank(getLong(r, "26")); ds.setRegionName(getString(r, "31", true)); ds.setAveragePointsPerRace(getInt(r, "32")); ds.setTotalLaps(getLong(r, "34")); ds.setLicenseClass(getString(r, "35", true)); ds.setAverageStartingPosition(getInt(r, "36")); ds.setRecordNumber(recordNumber); statList.add(ds); } output.setStats(statList); } catch (ParseException ex) { Logger.getLogger(DriverStatsParser.class.getName()).log(Level.SEVERE, null, ex); } return output; }
From source file:com.rylinaux.plugman.util.BukGetUtil.java
/** * Get the slug of the plugin./*from w ww . j av a2s . co m*/ * * @param name the name of the plugin. * @return the slug of the plugin. */ public static String getPluginSlug(String name) { HttpClient client = HttpClients.createMinimal(); HttpGet get = new HttpGet(API_BASE_URL + "search/slug/like/" + name + "?fields=plugin_name,slug"); try { HttpResponse response = client.execute(get); String body = IOUtils.toString(response.getEntity().getContent()); JSONArray array = (JSONArray) JSONValue.parse(body); for (int i = 0; i < array.size(); i++) { JSONObject json = (JSONObject) array.get(i); String pluginName = (String) json.get("plugin_name"); if (name.equalsIgnoreCase(pluginName)) return (String) json.get("slug"); } } catch (IOException e) { } return null; }
From source file:com.wso2.raspberrypi.apicalls.APICall.java
public static List<Zone> listZones() { List<Zone> zones = new ArrayList<Zone>(); Token token = getToken();/*from w w w . java 2 s.c o m*/ if (token != null) { HttpClient httpClient = new HttpClient(); try { HttpResponse httpResponse = httpClient.doGet(apiURLPrefix + "/conferences/2/iot/zones", "Bearer " + token.getAccessToken()); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == 200) { JSONParser parser = new JSONParser(); JSONArray jsonArray = (JSONArray) parser.parse(httpClient.getResponsePayload(httpResponse)); for (int i = 0; i < jsonArray.size(); i++) { JSONObject obj = (JSONObject) jsonArray.get(i); zones.add(new Zone((String) obj.get("id"), (String) obj.get("name"))); } } else { log.error("Could not get Zones. HTTP Status code: " + statusCode); } } catch (IOException e) { log.error("", e); } catch (ParseException e) { log.error("", e); } } return zones; }
From source file:msuresh.raftdistdb.RaftClient.java
public static void SetValue(String name, String key, String value) throws FileNotFoundException { if (key == null || key.isEmpty()) { return;//from ww w. j a v a2s. co m } File configFile = new File(Constants.STATE_LOCATION + name + ".info"); if (!configFile.exists() || configFile.isDirectory()) { FileNotFoundException ex = new FileNotFoundException(); throw ex; } try { System.out.println("Adding key .. hold on.."); String content = new Scanner(configFile).useDelimiter("\\Z").next(); JSONObject config = (JSONObject) (new JSONParser()).parse(content); Long numPart = (Long) config.get("countPartitions"); Integer shardId = key.hashCode() % numPart.intValue(); JSONArray memberJson = (JSONArray) config.get(shardId.toString()); List<Address> members = new ArrayList<>(); for (int i = 0; i < memberJson.size(); i++) { JSONObject obj = (JSONObject) memberJson.get(i); Long port = (Long) obj.get("port"); String address = (String) obj.get("address"); members.add(new Address(address, port.intValue())); } CopycatClient client = CopycatClient.builder(members).withTransport(new NettyTransport()).build(); client.open().join(); client.submit(new PutCommand(key, value)).get(); client.close().join(); while (client.isOpen()) { Thread.sleep(1000); } System.out.println("key " + key + " with value : " + value + " has been added to the cluster"); } catch (Exception ex) { System.out.println(ex.toString()); } }