List of usage examples for org.json.simple.parser JSONParser JSONParser
JSONParser
From source file:model.Post_store.java
public static int getlastid() { JSONParser parser = new JSONParser(); int lastid = 1; try {/*from www. j a v a2s . c o m*/ Object idObj = parser.parse(new FileReader(root + "posts/lastid.json")); JSONObject jsonObject = (JSONObject) idObj; String slastid = jsonObject.get("lastid").toString(); lastid = Integer.parseInt(slastid); //System.out.println(lastid); } catch (FileNotFoundException e) { JSONObject newIdObj = new JSONObject(); lastid = 1; newIdObj.put("lastid", lastid); try (FileWriter file = new FileWriter(root + "posts/lastid.json");) { file.write(newIdObj.toJSONString()); file.flush(); file.close(); } catch (IOException ex) { System.out.println(e); } } catch (IOException e) { System.out.println(e); } catch (ParseException e) { System.out.println(e); } return lastid; }
From source file:ch.uzh.phys.ecn.oboma.map.api.MapFactory.java
public static INodeMap buildDefaultSBBMap() throws Exception { NodeMap map = new NodeMap(); Random rand = new Random(); int stationCount = 0; int trainCount = 0; JSONParser parser = new JSONParser(); try {/*from www .ja va2s. c om*/ JSONArray stations = (JSONArray) parser.parse(Files.newBufferedReader(Paths.get("data/stations.json"))); for (Object o : stations) { JSONObject station = (JSONObject) o; String id = (String) station.get("id"); String name = (String) station.get("name"); JSONObject coord = (JSONObject) ((JSONObject) station.get("location")).get("wgs"); Double lat = (Double) coord.get("y"); Double lng = (Double) coord.get("x"); Node node = new Node(id, name, lat, lng, 0, 0); map.add(node); stationCount++; LOGGER.info(String.format("Station Node %s (%s) added", id, name)); } JSONArray connections = (JSONArray) parser .parse(Files.newBufferedReader(Paths.get("data/connections.json"))); for (Object o : connections) { JSONObject connection = (JSONObject) o; String from = (String) connection.get("from"); String to = (String) connection.get("to"); int time = (int) ((long) connection.get("time")); String id1 = String.format("%s-%s", from, to); String name1 = String.format("Train %s - %s", from, to); String id2 = String.format("%s-%s", to, from); String name2 = String.format("Train %s - %s", to, from); int seats = rand.nextInt(1000) + 1; Node node1 = new TrainNode(id1, name1, 0, 0, time, seats); Node node2 = new TrainNode(id2, name2, 0, 0, time, seats); try { map.add(node1, from, to); map.add(node2, to, from); trainCount++; LOGGER.info(String.format("Train Node %s (%s -> %s) added (%d seats)", id1, from, to, seats)); } catch (Exception pEx) { // either from or to do not exist } } LOGGER.info(String.format("%d stations added / %d trains added", stationCount, trainCount)); } catch (Exception pEx) { throw new Exception("Could not build map", pEx); } return map; }
From source file:com.serena.rlc.provider.servicenow.domain.ChangeRequest.java
public static ChangeRequest parseSingle(String options) { JSONParser parser = new JSONParser(); try {//from w ww . j av a 2 s . c o m Object parsedObject = parser.parse(options); ChangeRequest changeRequest = parseSingle( (JSONObject) getJSONValue((JSONObject) parsedObject, "result")); return changeRequest; } catch (ParseException e) { logger.error("Error while parsing input JSON - " + options, e); } return null; }
From source file:com.turt2live.xmail.api.Attachments.java
/** * Attempts to get an attachment from a JSON string. This will throw an IllegalArgumentException if * the json string is null or invalid./*from ww w. j ava 2s . c om*/ * * @param json the JSON string * * @return the attachment, or an UnknownAttachment if no match */ @SuppressWarnings("unchecked") public static Attachment getAttachment(String json) { if (json == null) { throw new IllegalArgumentException(); } JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory() { @Override public List<Object> creatArrayContainer() { return new LinkedList<Object>(); } @Override public Map<String, Object> createObjectContainer() { return new LinkedHashMap<String, Object>(); } }; Map<String, Object> map = new HashMap<String, Object>(); try { Map<?, ?> json1 = (Map<?, ?>) parser.parse(json, containerFactory); Iterator<?> iter = json1.entrySet().iterator(); // Type check while (iter.hasNext()) { Entry<?, ?> entry = (Entry<?, ?>) iter.next(); if (!(entry.getKey() instanceof String)) { throw new IllegalArgumentException("Not in <String, Object> format"); } } map = (Map<String, Object>) json1; } catch (ParseException e) { e.printStackTrace(); return null; } catch (IllegalArgumentException e) { e.printStackTrace(); return null; } XMail plugin = XMail.getInstance(); Attachment a = plugin.getMailServer().attemptAttachmentDecode(map); if (a != null) { return a; } a = plugin.getAttachmentHandlerRegistry().getAttachmentFromHandler(json); return a == null ? new UnknownAttachment(json) : a; }
From source file:capabilities.Browser.java
@Override public String adaptRole(String dbResult) throws Exception { // Variveis retornadas do WURFL em JSON String mobile_browser;/* w w w. ja v a 2 s .co 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:com.serena.rlc.provider.jenkins.domain.Job.java
public static List<Job> parse(String options) { List<Job> list = new ArrayList<>(); JSONParser parser = new JSONParser(); try {/*from w w w .j a v a 2s.co m*/ Object parsedObject = parser.parse(options); JSONArray array = (JSONArray) ((JSONObject) parsedObject).get("jobs"); for (Object object : array) { Job obj = new Job(); JSONObject jsonObject = (JSONObject) object; // JSONObject nameObject = (JSONObject)jsonObject.get("name"); // JSONObject displayNameObject = (JSONObject)jsonObject.get("displayName"); obj.setName((String) jsonObject.get("name")); obj.setDisplayName((String) jsonObject.get("displayName")); list.add(obj); } } catch (ParseException e) { logger.error("Error while parsing input JSON - " + options, e); } return list; }
From source file:connector.ISConnector.java
public static JSONObject processRequest(String servlet, byte[] query) { JSONObject response = null;//from w ww . java 2s. c om if (servlet != null && !servlet.startsWith("/")) servlet = "/" + servlet; try { // Establish HTTP connection with Identity Service URL url = new URL(CONTEXT_PATH + servlet); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //Create the form content try (OutputStream out = conn.getOutputStream()) { out.write(query); out.close(); } // Buffer the result into a string BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); conn.disconnect(); response = (JSONObject) new JSONParser().parse(sb.toString()); } catch (Exception e) { e.printStackTrace(); } return response; }
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"); }/*from w w w .j ava 2 s . c o m*/ String type = "mp3"; Song song = new Song(id, title, performer, source, thumbnail, type); songs.add(song); } return songs; }
From source file:manager.computerVisionManager.java
private static void getJson(String path) { System.out.println("Get Description from https://westus.api.cognitive.microsoft.com/vision/v1.0/describe"); try {//from w ww .ja v a2 s . c o m URIBuilder builder = new URIBuilder("https://westus.api.cognitive.microsoft.com/vision/v1.0/describe"); builder.setParameter("maxCandidates", "1"); URI uri = builder.build(); HttpPost request = new HttpPost(uri); request.setHeader("Content-Type", "application/json"); request.setHeader("Ocp-Apim-Subscription-Key", "d7f6ef12e41c4f8c8e72d12a890fa703"); // Request body StringEntity reqEntity = new StringEntity("{\"url\":\"" + path + "\"}"); System.out.println("Request String: " + reqEntity.toString()); request.setEntity(reqEntity); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { String respuesta = EntityUtils.toString(entity); JSONParser lector = new JSONParser(); StringReader SR = new StringReader(respuesta); try { JSONObject temp = (JSONObject) lector.parse(SR); json = (JSONObject) temp.get("description"); } catch (org.json.simple.parser.ParseException e) { System.err.println(e.getMessage()); } } } catch (IOException | URISyntaxException | ParseException e) { System.err.println(e.getMessage()); } }
From source file:autoancillarieslimited.action.item.DeleteFile.java
public static Item parserItem(String dataJson) { try {/*from w ww . j a va 2s . c o m*/ Item i = new Item(); JSONParser parser = new JSONParser(); Object obj = parser.parse(dataJson); JSONObject jsonObject = (JSONObject) obj; int id = Integer.parseInt((String) jsonObject.get("P0")); System.out.println(id); String file_delete = (String) jsonObject.get("P1"); i.setId(id); i.setImages(file_delete); return i; } catch (Exception ex) { return null; } }