List of usage examples for org.json.simple.parser JSONParser parse
public Object parse(Reader in) throws IOException, ParseException
From source file:capabilities.Browser.java
@Override public String adaptRole(String dbResult) throws Exception { // Variveis retornadas do WURFL em JSON String mobile_browser;/*from w ww .j a va 2 s. c o m*/ String mobile_browser_version; // Conversao do JSON de entrada para as variaveis respectivas JSONObject capabilities; JSONParser parser = new JSONParser(); capabilities = (JSONObject) parser.parse(dbResult); //JSONObject capabilities = (JSONObject) my_obj.get("capabilities"); System.out.println("\t" + capabilities); mobile_browser = (String) capabilities.get("mobile_browser"); mobile_browser_version = (String) capabilities.get("mobile_browser_version"); // Olhar as APIs compatveis em http://mobilehtml5.org/ // para possveis regras. // Criar um novo JSON e adicionar as informaes ele. JSONObject virtual = new JSONObject(); if (mobile_browser.equals("Firefox Mobile")) { virtual.put("luminosity", "true"); virtual.put("proximity", "true"); virtual.put("vibration", "true"); } else { virtual.put("luminosity", "false"); virtual.put("proximity", "false"); virtual.put("vibration", "false"); } if (mobile_browser.equals("Opera Mini")) { virtual.put("geolocation", "false"); } else { virtual.put("geolocation", "true"); } if (mobile_browser.equals("IEMobile")) { virtual.put("cameraAPI", "false"); virtual.put("orientation", "false"); } else { virtual.put("cameraAPI", "true"); virtual.put("orientation", "true"); } if (mobile_browser.equals("Chrome Mobile")) { virtual.put("webSpeechAPI", "true"); } else { virtual.put("webSpeechAPI", "false"); } // Adicionar esse novo JSON ao JSON de entrada e retorn-lo capabilities.put("virtual", virtual); return capabilities.toJSONString(); }
From source file:edu.pdx.konstan2.PortlandLive.responseParserFactory.java
public void parseArrivalsXML(String response, HashMap<String, Arrival> sMap) { try {/*from w w w. j a v a2s. c o m*/ JSONParser parser = new JSONParser(); JSONObject jobj = (JSONObject) parser.parse(response.toString()); JSONObject v = (JSONObject) jobj.get("resultSet"); JSONArray arr = (JSONArray) v.get("arrival"); Iterator<JSONObject> iter = arr.iterator(); while (iter.hasNext()) { Arrival t = new Arrival(iter.next()); sMap.put(t.id, t); } } catch (Exception e) { Log.d("exception", e.toString()); } }
From source file:me.uni.sushilkumar.geodine.util.YoutubeSearch.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request/*from w w w .j ava2s .c om*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException, SQLException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String type = request.getParameter("type"); String query = null; type += ""; if (type.equals("random")) { DBConnection con = new DBConnection(); ArrayList<String> cuisineList = con.getCuisineList(); Random generator = new Random(); query = cuisineList.get(generator.nextInt(cuisineList.size())); } else { query = request.getParameter("q"); } query += " recipe"; URL u = new URL("http://gdata.youtube.com/feeds/api/videos?q=" + URLEncoder.encode(query, "UTF-8") + "&max-results=1&v=2&alt=jsonc"); BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream())); JSONParser parser = new JSONParser(); Object obj = parser.parse(br); JSONObject json = (JSONObject) obj; JSONObject data = (JSONObject) json.get("data"); JSONArray items = (JSONArray) data.get("items"); Iterator<JSONObject> it = items.iterator(); if (it != null) { JSONObject item = it.next(); String id = (String) item.get("id"); String title = (String) item.get("title"); out.println(id); } else { out.println("Unable to fetch any video"); } } finally { out.close(); } }
From source file:capabilities.Display.java
@Override public String adaptRole(String dbResult) throws Exception { // Variveis retornadas do WURFL em JSON int resolution_width; int resolution_height; int columns;/* ww w . j a v a 2s .co m*/ int rows; int physical_screen_width; int physical_screen_height; String dual_orientation; // Conversao do JSON de entrada para as variaveis respectivas JSONObject capabilities; JSONParser parser = new JSONParser(); capabilities = (JSONObject) parser.parse(dbResult); //JSONObject capabilities = (JSONObject) my_obj.get("capabilities"); System.out.println("\t" + capabilities); resolution_width = Integer.parseInt((String) capabilities.get("resolution_width")); resolution_height = Integer.parseInt((String) capabilities.get("resolution_height")); columns = Integer.parseInt((String) capabilities.get("columns")); rows = Integer.parseInt((String) capabilities.get("rows")); physical_screen_width = Integer.parseInt((String) capabilities.get("physical_screen_width")); physical_screen_height = Integer.parseInt((String) capabilities.get("physical_screen_height")); dual_orientation = (String) capabilities.get("dual_orientation"); // Criar um novo JSON e adicionar as informaes ele. JSONObject virtual = new JSONObject(); if (physical_screen_width < physical_screen_height) { virtual.put("orientation_preferred", "portrait"); virtual.put("thumbs_only", "true"); } else { virtual.put("orientation_preferred", "landscape"); virtual.put("thumbs_only", "false"); } // Clculo da dimenso em polegadas da diagonal do dispositivo double diagonal = Math.sqrt( physical_screen_width * physical_screen_width + physical_screen_height * physical_screen_height); diagonal *= 0.039370; if (diagonal < 4) { virtual.put("average_size", "small_dispositive"); } else if (diagonal > 5.5) { virtual.put("average_size", "large_dispositive"); } else { virtual.put("average_size", "medium_dispositive"); } // Adicionar esse novo JSON ao JSON de entrada e retorn-lo capabilities.put("virtual", virtual); return capabilities.toJSONString(); }
From source file:edu.pdx.konstan2.PortlandLive.responseParserFactory.java
public void parseArrivals(String response, HashMap<String, Arrival> sMap) { try {//from www . jav a 2 s. c o m JSONParser parser = new JSONParser(); JSONObject jobj = (JSONObject) parser.parse(response.toString()); JSONObject v = (JSONObject) jobj.get("resultSet"); JSONArray arr = (JSONArray) v.get("arrival"); Iterator<JSONObject> iter = arr.iterator(); while (iter.hasNext()) { Arrival t = new Arrival(iter.next()); sMap.put(t.id, t); iter.remove(); } } catch (Exception e) { Log.d("exception", e.toString()); } }
From source file:com.Assignment4.Products.java
/** * converting integer into string and parsing it to jsonobject * @param s returns the query in the and executes the insert query * @throws ParseException/*from w w w . j a v a 2s .c o m*/ * @throws SQLException */ @POST @Path("/product") @Consumes(MediaType.APPLICATION_JSON) public void createProducts(String str) throws ParseException, SQLException { JSONParser jparser = new JSONParser(); JsonObject jobject = (JsonObject) jparser.parse(str); Object ID = jobject.get("id"); String ProductID = ID.toString(); int iD = Integer.parseInt(ProductID); Object Name = jobject.get("name"); String name = Name.toString(); Object Description = jobject.get("description"); String description = Description.toString(); Object Qty = jobject.get("quantity"); String quantity = Qty.toString(); int Quantity = Integer.parseInt(quantity); Connection conn = getConnection(); Statement s = conn.createStatement(); s.executeUpdate("INSERT INTO product VALUES ('" + iD + "','" + name + "','" + description + "','" + quantity + "' )"); }
From source file:hoot.services.utils.DbUtilsTest.java
@Test @Category(UnitTest.class) public void testEscapeJson() throws Exception { String expected = "{'INPUT1':'4835','INPUT2':'4836','OUTPUT_NAME':'Merged_525_stats','CONFLATION_TYPE':'Reference','GENERATE_REPORT':'false','TIME_STAMP':'1453777469448','REFERENCE_LAYER':'1','AUTO_TUNNING':'false','ADV_OPTIONS': {'map.cleaner.transforms': 'hoot::ReprojectToPlanarOp;hoot::DuplicateWayRemover;hoot::SuperfluousWayRemover;hoot::IntersectionSplitter;hoot::UnlikelyIntersectionRemover;hoot::DualWaySplitter;hoot::ImpliedDividedMarker;hoot::DuplicateNameRemover;hoot::SmallWayMerger;hoot::RemoveEmptyAreasVisitor;hoot::RemoveDuplicateAreaVisitor;hoot::NoInformationElementRemover', 'small.way.merger.threshold': '15', 'unify.optimizer.time.limit': '30', 'ogr.split.o2s': 'false', 'ogr.tds.add.fcsubtype': 'true', 'ogr.tds.structure': 'true', 'duplicate.name.case.sensitive': 'true', 'conflate.match.highway.classifier': 'hoot::HighwayRfClassifier', 'match.creators': 'hoot::HighwayMatchCreator;hoot::BuildingMatchCreator;hoot::ScriptMatchCreator,PoiGeneric.js;hoot::ScriptMatchCreator,LinearWaterway.js', 'merger.creators': 'hoot::HighwaySnapMergerCreator;hoot::BuildingMergerCreator;hoot::ScriptMergerCreator', 'search.radius.highway': '-1', 'highway.matcher.heading.delta': '5.0', 'highway.matcher.max.angle': '60', 'way.merger.min.split.size': '5', 'conflate.enable.old.roads': 'false', 'way.subline.matcher': 'hoot::MaximalNearestSublineMatcher', 'waterway.angle.sample.distance': '20.0', 'waterway.matcher.heading.delta': '150.0', 'waterway.auto.calc.search.radius': 'true', 'search.radius.waterway': '-1', 'waterway.rubber.sheet.minimum.ties': '5', 'waterway.rubber.sheet.ref': 'true', 'writer.include.debug': 'false'},'INPUT1_TYPE':'DB','INPUT2_TYPE':'DB','USER_EMAIL':'test@test.com'}"; String input = "{\"INPUT1\":\"4835\",\"INPUT2\":\"4836\",\"OUTPUT_NAME\":\"Merged_525_stats\",\"CONFLATION_TYPE\":\"Reference\",\"GENERATE_REPORT\":\"false\",\"TIME_STAMP\":\"1453777469448\",\"REFERENCE_LAYER\":\"1\",\"AUTO_TUNNING\":\"false\",\"ADV_OPTIONS\":\"-D \\\"map.cleaner.transforms=hoot::ReprojectToPlanarOp;hoot::DuplicateWayRemover;hoot::SuperfluousWayRemover;hoot::IntersectionSplitter;hoot::UnlikelyIntersectionRemover;hoot::DualWaySplitter;hoot::ImpliedDividedMarker;hoot::DuplicateNameRemover;hoot::SmallWayMerger;hoot::RemoveEmptyAreasVisitor;hoot::RemoveDuplicateAreaVisitor;hoot::NoInformationElementRemover\\\" -D \\\"small.way.merger.threshold=15\\\" -D \\\"unify.optimizer.time.limit=30\\\" -D \\\"ogr.split.o2s=false\\\" -D \\\"ogr.tds.add.fcsubtype=true\\\" -D \\\"ogr.tds.structure=true\\\" -D \\\"duplicate.name.case.sensitive=true\\\" -D \\\"conflate.match.highway.classifier=hoot::HighwayRfClassifier\\\" -D \\\"match.creators=hoot::HighwayMatchCreator;hoot::BuildingMatchCreator;hoot::ScriptMatchCreator,PoiGeneric.js;hoot::ScriptMatchCreator,LinearWaterway.js\\\" -D \\\"merger.creators=hoot::HighwaySnapMergerCreator;hoot::BuildingMergerCreator;hoot::ScriptMergerCreator\\\" -D \\\"search.radius.highway=-1\\\" -D \\\"highway.matcher.heading.delta=5.0\\\" -D \\\"highway.matcher.max.angle=60\\\" -D \\\"way.merger.min.split.size=5\\\" -D \\\"conflate.enable.old.roads=false\\\" -D \\\"way.subline.matcher=hoot::MaximalNearestSublineMatcher\\\" -D \\\"waterway.angle.sample.distance=20.0\\\" -D \\\"waterway.matcher.heading.delta=150.0\\\" -D \\\"waterway.auto.calc.search.radius=true\\\" -D \\\"search.radius.waterway=-1\\\" -D \\\"waterway.rubber.sheet.minimum.ties=5\\\" -D \\\"waterway.rubber.sheet.ref=true\\\" -D \\\"writer.include.debug=false\\\"\",\"INPUT1_TYPE\":\"DB\",\"INPUT2_TYPE\":\"DB\",\"USER_EMAIL\":\"test@test.com\"}"; String output = JsonUtils.escapeJson(input); JSONParser parser = new JSONParser(); JSONObject exJson = (JSONObject) parser.parse(expected.replaceAll("'", "\"")); JSONObject outJson = (JSONObject) parser.parse(output.replaceAll("\\\\\"", "\"")); Assert.assertEquals(exJson, outJson); }
From source file:Json.JsonWrite.java
public void jsonRead(String patchName) throws IOException, ParseException { JSONParser parser = new JSONParser(); JSONObject object = (JSONObject) parser.parse(new FileReader(patchName)); this.patch = (String) object.get("patch"); this.page = (String) object.get("page"); this.eddWay = (String) object.get("eddWay"); this.proffName = (String) object.get("proffName"); this.YStart = (String) object.get("yearStart"); this.YEnd = (String) object.get("yearEnd"); this.EddName = (String) object.get("eddName"); //System.out.println("Json.JsonWrite.jsonRead()"); }
From source file:org.uom.fit.level2.datavis.repository.ChatServicesImpl.java
@Override public JSONArray getAll() { try {/*from w w w . ja va2 s . c om*/ Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("datarepo"); DBCollection collection = db.getCollection("user"); DBCursor cursor = collection.find(); JSON json = new JSON(); String dataUser = json.serialize(cursor); JSONParser parser = new JSONParser(); Object obj = parser.parse(dataUser); JSONArray jsonarray = (JSONArray) obj; return jsonarray; } catch (Exception e) { System.out.println("Exception Error getAll"); return null; } }
From source file:com.github.lgi2p.obirs.utils.IndexerJSON.java
public void indexItem(String json) throws IOException, ParseException { JSONParser parser = new JSONParser(); Object obj;//w w w .jav a2 s .c o m obj = parser.parse(json); JSONObject jsonObject = (JSONObject) obj; String uri = (String) jsonObject.get("uri").toString(); String label = (String) jsonObject.get("label"); String href = (String) jsonObject.get("href"); URI itemUri = URIFactoryMemory.getSingleton().getURI(uri); Set<URI> itemAnnotations = new HashSet(); ItemMetadata meta = new ItemMetadata(uri, label, href); JSONArray conceptIds = (JSONArray) jsonObject.get("annots"); for (int i = 0; i < conceptIds.size(); i++) { String conceptURI = (String) conceptIds.get(i); URI uriConcept = URIFactory.getURI(conceptURI); itemAnnotations.add(uriConcept); } items.add(new Item(itemUri, itemAnnotations)); metadata.put(itemUri, meta); }