List of usage examples for org.json.simple JSONArray size
public int size()
From source file:com.zb.app.biz.service.WeixinTest.java
public String getFakeid(String openid) { if (isLogin) { GetMethod get = new GetMethod("https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&token=" + token + "&lang=zh_CN&pagesize=10&pageidx=0&type=0"); get.setRequestHeader("Cookie", this.cookiestr); get.setRequestHeader("Host", "mp.weixin.qq.com"); get.setRequestHeader("Referer", "https://mp.weixin.qq.com/cgi-bin/message?t=message/list&count=20&day=7&token=" + token + "&lang=zh_CN"); get.setRequestHeader("Content-Type", "text/html;charset=UTF-8"); try {/*from w w w. j ava 2 s . c om*/ int code = httpClient.executeMethod(get); System.out.println(code); if (HttpStatus.SC_OK == code) { System.out.println("Fake Success"); String str = get.getResponseBodyAsString(); System.out.println(str.length()); // String userjson = StringUtils.substringBetween(str, // "<script id=\"json-friendList\" type=\"json/text\">", "</script>"); String userjson = StringUtils.substringBetween(str, "\"contacts\":", "})"); System.out.println(userjson); JSONParser parser = new JSONParser(); try { JSONArray array = (JSONArray) parser.parse(userjson); for (int i = 0; i < array.size(); i++) { JSONObject obj = (JSONObject) array.get(i); String fakeid = obj.get("id").toString(); if (compareFakeid(fakeid, openid)) { return fakeid; } } } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } else { login(); return getFakeid(openid); } return null; }
From source file:net.bashtech.geobot.JSONUtil.java
public static String BOIItemInfo(String searchTerm) { String modified = searchTerm.toLowerCase().replace(" a ", "").replace(" ", "").replace("/", "") .replace("'", "").replace("the", "").replace("<", "<").replace("1", "one").replace("2", "two") .replace("3", "three").replace("20", "twenty").replace("-", "").replace(".", "").replace("!", "") .replace("=", "").replace("equals", ""); int found = -1; try {/*w w w . j a va 2 s. c o m*/ JSONParser parser = new JSONParser(); Object obj = parser.parse(BotManager.getRemoteContent("http://coebot.tv/boiitemsarray.json")); JSONArray topArray = (JSONArray) obj; for (int i = 0; i < topArray.size(); i++) { JSONObject tempobj = (JSONObject) topArray.get(i); String orig = (String) tempobj.get("title"); if (modified .equalsIgnoreCase(orig.toLowerCase().replace(" a ", "").replace(" ", "").replace("/", "") .replace("'", "").replace("the", "").replace("<", "<").replace("1", "one") .replace("2", "two").replace("3", "three").replace("20", "twenty").replace("-", "") .replace(".", "").replace("!", "").replace("=", "").replace("equals", ""))) { found = i; break; } } if (found > -1) { JSONObject item = (JSONObject) topArray.get(found); JSONArray info = (JSONArray) item.get("info"); String retString = ""; for (int i = 0; i < info.size(); i++) { if (retString.length() + ((String) info.get(i)).length() < 245) retString += info.get(i) + "; "; else break; } retString = retString.trim(); retString = retString.substring(0, retString.length() - 1); return retString; } else { return "Item Not Found"; } } catch (Exception e) { e.printStackTrace(); return "Error"; } }
From source file:de.mpg.imeji.presentation.servlet.autocompleter.java
/** * Parse a json input from Google Geo API * // ww w . j a v a2 s . c o m * @param google * @return * @throws IOException */ @SuppressWarnings("unchecked") private String parseGoogleGeoAPI(String google) throws IOException { JSONObject obj = (JSONObject) JSONValue.parse(google); JSONArray array = (JSONArray) obj.get("results"); JSONArray result = new JSONArray(); for (int i = 0; i < array.size(); ++i) { JSONObject parseObject = (JSONObject) array.get(i); JSONObject sendObject = new JSONObject(); sendObject.put("label", parseObject.get("formatted_address")); sendObject.put("value", parseObject.get("formatted_address")); JSONObject location = (JSONObject) ((JSONObject) parseObject.get("geometry")).get("location"); sendObject.put("latitude", location.get("lat")); sendObject.put("longitude", location.get("lng")); result.add(sendObject); } StringWriter out = new StringWriter(); result.writeJSONString(out); return out.toString(); }
From source file:net.bashtech.geobot.JSONUtil.java
public static ArrayList<String> tmiChatters(String channel) { try {/*from www . ja va2 s. co m*/ JSONParser parser = new JSONParser(); Object obj = parser.parse( BotManager.getRemoteContent("https://tmi.twitch.tv/group/user/" + channel + "/chatters")); JSONObject jsonObject = (JSONObject) obj; JSONObject chatters = (JSONObject) jsonObject.get("chatters"); JSONArray viewers = (JSONArray) chatters.get("viewers"); JSONArray moderators = (JSONArray) chatters.get("moderators"); for (int i = 0; i < moderators.size(); i++) { viewers.add(moderators.get(i)); } return viewers; } catch (Exception ex) { System.out.println("Failed to get chatters"); return null; } }
From source file:net.bashtech.geobot.JSONUtil.java
public static String steam(String userID, String retValues) { String api_key = BotManager.getInstance().SteamAPIKey; try {//from w w w .j a v a 2 s .c o m JSONParser parser = new JSONParser(); Object obj = parser.parse(BotManager .getRemoteContent("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?steamids=" + userID + "&key=" + api_key)); JSONObject jsonObject = (JSONObject) obj; JSONObject response = (JSONObject) (jsonObject.get("response")); JSONArray players = (JSONArray) response.get("players"); if (players.size() > 0) { JSONObject index0 = (JSONObject) players.get(0); String profileurl = (String) index0.get("profileurl"); String gameextrainfo = (String) index0.get("gameextrainfo"); String gameserverip = (String) index0.get("gameserverip"); String gameid = (String) index0.get("gameid"); if (retValues.equals("profile")) return JSONUtil.shortenUrlTinyURL(profileurl); else if (retValues.equals("game")) return (gameextrainfo != null ? gameextrainfo : "(unavailable)"); else if (retValues.equals("server")) return (gameserverip != null ? gameserverip : "(unavailable)"); else if (retValues.equals("store")) return (gameid != null ? "http://store.steampowered.com/app/" + gameid : "(unavailable)"); else return "Profile: " + JSONUtil.shortenUrlTinyURL(profileurl) + (gameextrainfo != null ? ", Game: " + gameextrainfo : "") + (gameserverip != null ? ", Server: " + gameserverip : ""); } else { return "Error querying API"; } } catch (Exception ex) { System.out.println("Failed to query Steam API"); return "Error querying API"; } }
From source file:net.bashtech.geobot.JSONUtil.java
public static String getGameChannel(String gameName) { gameName = gameName.replaceAll(" ", "+"); try {//from w w w . j a v a2s. c om JSONParser parser = new JSONParser(); Object obj = parser.parse( BotManager.getRemoteContent("https://api.twitch.tv/kraken/search/streams?q=" + gameName)); JSONObject jsonObject = (JSONObject) obj; Long total = (Long) jsonObject.get("_total"); if (total > 0) { JSONArray streams = (JSONArray) jsonObject.get("streams"); int numStreams = streams.size(); int randomChannel = (int) (Math.random() * (numStreams - 1)); JSONObject stream = (JSONObject) streams.get(randomChannel); JSONObject channel = (JSONObject) stream.get("channel"); String url = (String) channel.get("display_name"); return url; } else return "No other channels playing this game"; } catch (Exception ex) { ex.printStackTrace(); return "Error Querying API"; } }
From source file:com.gmail.bleedobsidian.areaprotect.Updater.java
/** * Query ServerMods API for project variables. * // w w w .j a v a 2 s .c o m * @return If successful or not. */ private boolean query() { try { final URLConnection con = this.url.openConnection(); con.setConnectTimeout(5000); if (this.apiKey != null) { con.addRequestProperty("X-API-Key", this.apiKey); } con.addRequestProperty("User-Agent", this.plugin.getName() + " Updater"); con.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.result = UpdateResult.ERROR_ID; return false; } this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get("name"); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get("downloadUrl"); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get("releaseType"); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get("gameVersion"); return true; } catch (IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.result = UpdateResult.ERROR_APIKEY; } else { this.result = UpdateResult.ERROR_SERVER; } return false; } }
From source file:com.optimizely.ab.config.parser.JsonSimpleConfigParser.java
private List<Experiment> parseExperiments(JSONArray experimentJson, String groupId) { List<Experiment> experiments = new ArrayList<Experiment>(experimentJson.size()); for (Object obj : experimentJson) { JSONObject experimentObject = (JSONObject) obj; String id = (String) experimentObject.get("id"); String key = (String) experimentObject.get("key"); String status = (String) experimentObject.get("status"); JSONArray audienceIdsJson = (JSONArray) experimentObject.get("audienceIds"); List<String> audienceIds = new ArrayList<String>(audienceIdsJson.size()); for (Object audienceIdObj : audienceIdsJson) { audienceIds.add((String) audienceIdObj); }//from ww w . j a va 2 s. c o m // parse the child objects List<Variation> variations = parseVariations((JSONArray) experimentObject.get("variations")); Map<String, String> userIdToVariationKeyMap = parseForcedVariations( (JSONObject) experimentObject.get("forcedVariations")); List<TrafficAllocation> trafficAllocations = parseTrafficAllocation( (JSONArray) experimentObject.get("trafficAllocation")); experiments.add(new Experiment(id, key, status, audienceIds, variations, userIdToVariationKeyMap, trafficAllocations, groupId)); } return experiments; }
From source file:com.capitalone.dashboard.client.project.ProjectDataClientImpl.java
/** * Updates the MongoDB with a JSONArray received from the source system * back-end with story-based data.//from w w w . j a v a2 s . c om * * @param tmpMongoDetailArray * A JSON response in JSONArray format from the source system * @param featureCollector * @return * @return */ @SuppressWarnings("unchecked") protected void updateMongoInfo(JSONArray tmpMongoDetailArray) { try { JSONObject dataMainObj = new JSONObject(); for (int i = 0; i < tmpMongoDetailArray.size(); i++) { if (dataMainObj != null) { dataMainObj.clear(); } dataMainObj = (JSONObject) tmpMongoDetailArray.get(i); Scope scope = new Scope(); @SuppressWarnings("unused") // ? boolean deleted = this .removeExistingEntity(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid"))); // collectorId scope.setCollectorId(featureCollectorRepository.findByName(Constants.VERSIONONE).getId()); // ID; scope.setpId(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid"))); // name; scope.setName(TOOLS.sanitizeResponse((String) dataMainObj.get("Name"))); // beginDate; scope.setBeginDate( TOOLS.toCanonicalDate(TOOLS.sanitizeResponse((String) dataMainObj.get("BeginDate")))); // endDate; scope.setEndDate( TOOLS.toCanonicalDate(TOOLS.sanitizeResponse((String) dataMainObj.get("EndDate")))); // changeDate; scope.setChangeDate( TOOLS.toCanonicalDate(TOOLS.sanitizeResponse((String) dataMainObj.get("ChangeDate")))); // assetState; scope.setAssetState(TOOLS.sanitizeResponse((String) dataMainObj.get("AssetState"))); // isDeleted; scope.setIsDeleted(TOOLS.sanitizeResponse((String) dataMainObj.get("IsDeleted"))); // path; String projPath = new String(scope.getName()); List<String> projList = (List<String>) dataMainObj.get("ParentAndUp.Name"); if (projList != null) { for (String proj : projList) { projPath = proj + "-->" + projPath; } projPath = "All-->" + projPath; } else { projPath = "All-->" + projPath; } scope.setProjectPath(TOOLS.sanitizeResponse(projPath)); try { projectRepo.save(scope); } catch (Exception e) { LOGGER.error("Unexpected error caused when attempting to save data\nCaused by: " + e.getCause(), e); } } } catch (Exception e) { LOGGER.error("FAILED: " + e.getMessage() + ", " + e.getClass()); } }
From source file:com.appcelerator.titanium.desktop.ui.wizard.TiManifestTest.java
protected void assertTiManifestContents(File file, final String appId, final String appName, final String guid, final String version, final String description, final String publisher, final String url, Set<String> platforms, String runtime, boolean release, String visibility, boolean showSplash) throws IOException, ParseException, FileNotFoundException { JSONParser parser = new JSONParser(); JSONObject resultJSON = null;//w ww. j ava 2s.c o m FileReader reader = null; try { reader = new FileReader(file); resultJSON = (JSONObject) parser.parse(reader); } finally { if (reader != null) { reader.close(); } } assertNotNull(resultJSON); assertEquals("App ID didn't match", appId, resultJSON.get(TiManifest.APPID)); assertEquals("App name didn't match", appName, resultJSON.get(TiManifest.APPNAME)); assertEquals("App version didn't match", version, resultJSON.get(TiManifest.APPVERSION)); assertEquals("App description didn't match", description, resultJSON.get(TiManifest.DESC)); assertEquals("App GUID didn't match", guid, resultJSON.get(TiManifest.GUID)); assertEquals("MID didn't match", TitaniumCorePlugin.getMID(), resultJSON.get(TiManifest.MID)); assertEquals("'noinstall' value was incorrect", !showSplash, resultJSON.get(TiManifest.NO_INSTALL)); JSONArray platformsArray = (JSONArray) resultJSON.get(TiManifest.PLATFORMS); assertEquals("'platforms' array size didn't match", platforms.size(), platformsArray.size()); for (String platform : platforms) { assertTrue("'platforms' array didn't contain expected value: " + platform, platformsArray.contains(platform)); } assertEquals("App publisher didn't match", publisher, resultJSON.get(TiManifest.PUBLISHER)); assertEquals("'release' boolean didn't match", release, resultJSON.get(TiManifest.RELEASE)); JSONObject runtimeObj = (JSONObject) resultJSON.get(TiManifest.RUNTIME); assertEquals("'runtime' didn't match", runtime, runtimeObj.get(TiManifest.PACKAGE)); assertEquals("App URL didn't match", url, resultJSON.get(TiManifest.URL)); assertEquals("Visibility is incorrect", visibility, resultJSON.get(TiManifest.VISIBILITY)); }