List of usage examples for org.json.simple.parser JSONParser parse
public Object parse(Reader in) throws IOException, ParseException
From source file:buspathcontroller.JSONFileParser.java
public void generateAllStops() { JSONParser parser = new JSONParser(); try {//from w w w. ja va2 s .c o m PrintWriter writer = new PrintWriter("/Users/Zhaowei/Desktop/BusPath/allStops.txt"); Object obj = parser.parse(new FileReader("/Users/Zhaowei/Desktop/BusPath/RawJSON/StopList.json")); JSONObject jsonObject = (JSONObject) obj; JSONArray routes = (JSONArray) jsonObject.get("stops"); Iterator iterator = routes.iterator(); while (iterator.hasNext()) { JSONObject stop = (JSONObject) ((JSONObject) iterator.next()).get("stop"); writer.println(stop.get("stopnumber") + ";" + stop.get("stoptitle") + ";" + stop.get("stoplat") + ";" + stop.get("stoplng")); } writer.close(); } catch (Exception e) { System.out.println(e); } }
From source file:com.thesmartweb.swebrank.BingResults.java
/** * Class to get the results number from Bing in order to use it in NWD * @param quer the query to get the results for * @param config_path the path with the configuration file (api keys for bing) * @return the number of the results for a certain query *//*from w w w. j a va 2s . c o m*/ public Long Get_Results_Number(String quer, String config_path) { try { long results_number = 0; //we check if we have an extra useless + in the end String check_quer = quer.substring(quer.length() - 1, quer.length()); char plus = "+".charAt(0); char check_plus = check_quer.charAt(0); if (check_plus == plus) { quer = quer.substring(0, quer.length() - 1); } quer = quer.replace("+", "%20"); //we connect through the Bing search api URL azure_url = new URL( "https://api.datamarket.azure.com/Bing/Search/Composite?Sources=%27web%27&Query=%27" + quer + "%27&$format=JSON"); APIconn apicon = new APIconn(); String line = apicon.azureconnect(azure_url, config_path); if ((!line.equalsIgnoreCase("fail")) && (!line.equalsIgnoreCase("insufficient")) && (!line.equalsIgnoreCase("provided"))) { //Create a parser of the json JSONParser parser = new JSONParser(); //Create the map Map json = (Map) parser.parse(line); // Get a set of the entries Set set = json.entrySet(); Object[] arr = set.toArray(); Map.Entry entry = (Map.Entry) arr[0]; //get to second level of yahoo json String you = entry.getValue().toString(); json = (Map) parser.parse(you); set = json.entrySet(); arr = set.toArray(); entry = (Map.Entry) arr[0]; you = entry.getValue().toString(); Object parse = parser.parse(you); JSONArray json_new = (JSONArray) parse; json = (Map) json_new.get(0); set = json.entrySet(); arr = set.toArray(); Map.Entry[] entries_bing = null; int k = 0; Iterator new_iterator = set.iterator(); while (new_iterator.hasNext()) { Object next = new_iterator.next(); Map.Entry next_entry = (Map.Entry) next; if (next_entry.getKey().toString().equalsIgnoreCase("WebTotal")) { results_number = Long.parseLong(next_entry.getValue().toString()); } } } return results_number; } catch (MalformedURLException | ParseException | java.lang.ArrayIndexOutOfBoundsException | java.lang.NullPointerException | NumberFormatException ex) { Logger.getLogger(BingResults.class.getName()).log(Level.SEVERE, null, ex); long results_number = 0; return results_number; } }
From source file:org.kitodo.data.elasticsearch.index.type.FilterTypeTest.java
@Test public void shouldCreateDocument() throws Exception { FilterType propertyType = new FilterType(); JSONParser parser = new JSONParser(); Filter property = prepareData().get(0); HttpEntity document = propertyType.createDocument(property); JSONObject actual = (JSONObject) parser.parse(EntityUtils.toString(document)); JSONObject expected = (JSONObject) parser.parse("{\"value\":\"\\\"id:1\\\"\",\"user\":1}"); assertEquals("Filter JSONObject doesn't match to given JSONObject!", expected, actual); property = prepareData().get(1);/*from w w w .ja v a 2 s .com*/ document = propertyType.createDocument(property); actual = (JSONObject) parser.parse(EntityUtils.toString(document)); expected = (JSONObject) parser.parse("{\"value\":\"\\\"id:2\\\"\",\"user\":1}"); assertEquals("Filter JSONObject doesn't match to given JSONObject!", expected, actual); }
From source file:minor.stockQuote.StockData.java
public List<StockDetails> getStockData(String ticker) { /*/* w w w .ja v a 2 s .com*/ if(ticker.length() > 5 || ticker.length() < 3){ //System.out.println("-----------------------------------------------------------------------------------------------------"+ticker); return null; } */ //else { String requestQuery = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + ticker + "%22)%0A%09%09" + "&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback="; //String requestQuery ="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20%3D%20"+ticker+"%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback="; //System.out.println(requestQuery); ArrayList<String> stockdetails = new ArrayList<String>(); URL url; try { url = new URL(requestQuery); URLConnection connection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); //System.out.println("jjjj"+in.readLine()); JSONParser jsonParser = new JSONParser(); try { JSONObject jsonObject = (JSONObject) jsonParser.parse(in); //System.out.println(jsonObject); JSONObject query = (JSONObject) jsonObject.get("query"); JSONObject results = (JSONObject) query.get("results"); JSONObject quote = (JSONObject) results.get("quote"); //System.out.println("iiiii"+quote.toJSONString()); stockdetails.add(quote.get("Change").toString()); stockdetails.add(quote.get("LastTradePriceOnly").toString()); stockdetails.add(quote.get("PERatio").toString()); stockdetails.add(quote.get("DaysLow").toString()); stockdetails.add(quote.get("DaysHigh").toString()); stockdetails.add(quote.get("Name").toString()); stockdetails.add(quote.get("Open").toString()); stockdetails.add(quote.get("Volume").toString()); stockdetails.add(quote.get("Ask").toString()); stockdetails.add(quote.get("AverageDailyVolume").toString()); stockdetails.add(quote.get("LastTradeDate").toString()); stockdetails.add(quote.get("EBITDA").toString()); stockdetails.add(quote.get("DaysRange").toString()); stockdetails.add(quote.get("FiftydayMovingAverage").toString()); stockdetails.add(quote.get("PreviousClose").toString()); stockdetails.add(quote.get("ChangeinPercent").toString()); stockdetails.add(quote.get("PEGRatio").toString()); stockdetails.add(quote.get("Symbol").toString()); stockdetails.add(quote.get("YearRange").toString()); stockdetails.add(quote.get("DaysValueChange").toString()); stockdetails.add(quote.get("StockExchange").toString()); stockdetails.add(quote.get("PercentChange").toString()); } catch (ParseException ex) { Logger.getLogger(StockData.class.getName()).log(Level.SEVERE, null, ex); } catch (NullPointerException ne) { } } catch (IOException e) { System.out.println(e); } for (String s : stockdetails) { System.out.println(s); } StockDetails obj = new StockDetails(stockdetails); //System.out.println("dddddD"+obj.toString()); List<StockDetails> sdList = new ArrayList<StockDetails>(); sdList.add(obj); /* for(StockDetails s: sdList){ System.out.println("ddfdfdf"+s.getChange() + s.getDaysHigh()); } */ return sdList; //} }
From source file:fi.aalto.drumbeat.apicalls.bimserver.BIMServerJSONApi.java
private JSONObject http(String url, String body) { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpPost request = new HttpPost(url); StringEntity params = new StringEntity(body); request.addHeader("content-type", "application/json"); request.setEntity(params);//w ww . ja v a2 s . c o m HttpResponse http_result = httpClient.execute(request); String json = EntityUtils.toString(http_result.getEntity(), "UTF-8"); System.out.println("result: " + json); try { JSONParser parser = new JSONParser(); Object resultObject = parser.parse(json); if (resultObject instanceof JSONObject) { JSONObject result = (JSONObject) resultObject; return result; } } catch (Exception e) { e.printStackTrace(); } } catch (IOException ex) { ex.printStackTrace(); } return null; }
From source file:com.lullabot.android.apps.iosched.ui.TwitterStreamFragment.java
public ArrayList<Tweet> getTweets(String searchTerm, int page) { String searchUrl = "http://search.twitter.com/search.json?q=#" + searchTerm + "&rpp=50&page=" + page; ArrayList<Tweet> tweets = new ArrayList<Tweet>(); HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(searchUrl); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = null;//from w ww . j a v a 2 s. co m try { responseBody = client.execute(get, responseHandler); } catch (Exception ex) { ex.printStackTrace(); } JSONObject jsonObject = null; JSONParser parser = new JSONParser(); try { Object obj = parser.parse(responseBody); jsonObject = (JSONObject) obj; } catch (Exception ex) { Log.v("TEST", "Exception: " + ex.getMessage()); } JSONArray arr = null; try { Object j = jsonObject.get("results"); arr = (JSONArray) j; } catch (Exception ex) { Log.v("TEST", "Exception: " + ex.getMessage()); } for (Object t : arr) { Tweet tweet = new Tweet(((JSONObject) t).get("from_user").toString(), ((JSONObject) t).get("text").toString(), ((JSONObject) t).get("profile_image_url").toString()); tweets.add(tweet); } return tweets; }
From source file:org.kitodo.data.elasticsearch.index.type.BatchTypeTest.java
@Test public void shouldCreateDocument() throws Exception { BatchType batchType = new BatchType(); JSONParser parser = new JSONParser(); Batch batch = prepareData().get(0);/*from w w w.j a va 2 s . c om*/ HttpEntity document = batchType.createDocument(batch); JSONObject actual = (JSONObject) parser.parse(EntityUtils.toString(document)); JSONObject expected = (JSONObject) parser .parse("{\"title\":\"Batch1\",\"type\":\"LOGISTIC\"," + "\"processes\":[{\"id\":1},{\"id\":2}]}"); assertEquals("Batch JSONObject doesn't match to given JSONObject!", expected, actual); batch = prepareData().get(1); document = batchType.createDocument(batch); actual = (JSONObject) parser.parse(EntityUtils.toString(document)); expected = (JSONObject) parser.parse("{\"title\":\"Batch2\",\"type\":null,\"processes\":[]}"); assertEquals("Batch JSONObject doesn't match to given JSONObject!", expected, actual); }
From source file:com.modeln.batam.connector.ConnectorCml.java
/** * Execute main logic./*from ww w . j av a2s .com*/ */ private void execute() { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; //Load property file. ConfigHelper.loadProperties(propertyFile); if (CREATE_BUILD_ACTION.equals(action)) { BuildEntry build = BuildEntry.fromJSON(jsonObject); ConnectorHelper.createBuild(build); } else if (UPDATE_BUILD_ACTION.equals(action)) { BuildEntry build = BuildEntry.fromJSON(jsonObject); ConnectorHelper.updateBuild(build); } else if (RUN_ANALYSIS_ACTION.equals(action)) { BuildEntry build = BuildEntry.fromJSON(jsonObject); ConnectorHelper.runAnalysis(build); } else if (CREATE_REPORT_ACTION.equals(action)) { ReportEntry report = ReportEntry.fromJSON(jsonObject); ConnectorHelper.createReport(report); } else if (UPDATE_REPORT_ACTION.equals(action)) { ReportEntry report = ReportEntry.fromJSON(jsonObject); ConnectorHelper.updateReport(report); } else if (CREATE_TEST_ACTION.equals(action)) { TestEntry test = TestEntry.fromJSON(jsonObject); ConnectorHelper.createTest(test); } else if (UPDATE_TEST_ACTION.equals(action)) { TestEntry test = TestEntry.fromJSON(jsonObject); ConnectorHelper.updateTest(test); } else { System.out.println("action " + action + " not allowed."); } } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } }
From source file:com.baystep.jukeberry.JsonConfiguration.java
public void load(String fileName) { BerryLogger.LOG.info("Loading configuration file..."); File configFile = new File(fileName); if (configFile.exists()) { JSONParser jparser = new JSONParser(); try {// ww w. j av a 2s. c om Object obj = jparser.parse(new FileReader(configFile)); jsonConfig = (JSONObject) obj; if (jsonConfig.containsKey("disable")) { String dOpt = (String) jsonConfig.get("disable"); setDisableOption(dOpt); } if (jsonConfig.containsKey("http server")) { JSONObject httpObj = (JSONObject) jsonConfig.get("http server"); if (httpObj.containsKey("port")) httpPort = getInt(httpObj, "port"); } if (jsonConfig.containsKey("websocket server")) { JSONObject wsObj = (JSONObject) jsonConfig.get("websocket server"); if (wsObj.containsKey("port")) websocketPort = getInt(wsObj, "port"); } if (jsonConfig.containsKey("music player")) { JSONObject mpObj = (JSONObject) jsonConfig.get("music player"); if (mpObj.containsKey("start service")) { mpStartService = (String) mpObj.get("start service"); } if (mpObj.containsKey("local directories")) { mpDirectories = getStringArray(mpObj, "local directories"); } if (mpObj.containsKey("sources")) { mpSources = getSourceDescriptionArray(mpObj, "sources"); } } } catch (IOException | org.json.simple.parser.ParseException ex) { BerryLogger.LOG.log(Level.WARNING, "Failed to parse configuration file: {0}", ex.getMessage()); } } else { BerryLogger.LOG.warning("Failed to load the configuration file!"); } }
From source file:com.opensoc.parsing.test.BasicLancopeParserTest.java
/** * Test method for {@link com.opensoc.parsing.parsers.BasicLancopeParser#parse(byte[])}. * @throws Exception /* w w w.ja v a2s. c om*/ * @throws IOException */ public void testParse() throws IOException, Exception { for (String inputString : getInputStrings()) { JSONObject parsed = parser.parse(inputString.getBytes()); assertNotNull(parsed); System.out.println(parsed); JSONParser parser = new JSONParser(); Map<?, ?> json = null; try { json = (Map<?, ?>) parser.parse(parsed.toJSONString()); assertEquals(true, validateJsonData(super.getSchemaJsonString(), json.toString())); } catch (ParseException e) { e.printStackTrace(); } } }