List of usage examples for com.google.gson JsonParser JsonParser
@Deprecated
public JsonParser()
From source file:serverSocket.java
License:Apache License
@OnOpen public void start(Session session) { this.session = session; connections.add(this); try {/*from w w w .j a v a2s .co m*/ synchronized (this) { JsonObject ret = new JsonObject(); ret.addProperty("access_key", uuid); this.session.getBasicRemote().sendText(ret.toString()); connPool.put(uuid, session); } } catch (IOException e) { e.printStackTrace(); try { this.session.close(); } catch (IOException e1) { // Ignore } } jsonParser = new JsonParser(); //tricky, put tweets_data in this path //System.out.println(this.getClass().getResource("").getPath()); JsonArray rawlist = new JsonArray(); try { BufferedReader br = new BufferedReader( new InputStreamReader(serverSocket.class.getResourceAsStream("/tweets_data.txt"))); String line = br.readLine(); rawlist = jsonParser.parse(line).getAsJsonArray(); br.close(); //System.out.println(list); } catch (IOException e) { System.out.println(this.getClass().getResource("").getPath()); e.printStackTrace(); } list = sortJson(rawlist); }
From source file:PanicDetect.java
License:Apache License
private void listRegex() { try {//w w w . j a v a2 s . c om String result = RunnerRepository.getRPCClient() .execute("panicDetectConfig", new Object[] { RunnerRepository.getUser(), "list" }).toString(); JsonElement jelement = new JsonParser().parse(result); JsonObject main = jelement.getAsJsonObject(); JsonObject regex = main.getAsJsonObject(RunnerRepository.getUser()); Iterator<Map.Entry<String, JsonElement>> iter = regex.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, JsonElement> n = iter.next(); String id = n.getKey(); JsonElement content = n.getValue(); JsonObject ob = content.getAsJsonObject(); String exp = ob.get("expression").getAsString(); String en = ob.get("enabled").getAsString(); MyPanel panel = new MyPanel(exp, Boolean.parseBoolean(en), id); addPanel(panel); } } catch (Exception e) { e.printStackTrace(); } }
From source file:jsonSploit.java
/** * @param args the command line arguments *//*from ww w . j av a 2s . co m*/ public static void main(String[] args) { // TODO code application logic here Gson gson = new Gson(); System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON"); String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json"; System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); } if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } String jsonResult = sb.toString(); System.out.println(sb.toString()); System.out.println("\n\n--------------------JSON OBJECT DISPLAY----------------------------\n\n"); // convertimos el string a json Object JSONObject jsonObj = new JSONObject(jsonResult); // System.out.println("LA CADENA JSON CONVERTIDA EN OBJETO ES>"); System.out.println(jsonObj.toString()); System.out .println("\n\n--------------------- OBTENER ARRAYS DEL OBJETO JSON---------------------------\n\n"); JSONArray jsonArray = new JSONArray(); jsonArray.put(jsonObj); gson = new Gson(); Iterator x = jsonObj.keys(); while (x.hasNext()) { String key = (String) x.next(); jsonArray.put(jsonObj.get(key)); System.out.println(key); } System.out .println("\n\n--------------------- OBTENER ARRAYS DEL OBJETO JSON---------------------------\n\n"); JsonParser jsonParser = new JsonParser(); JsonObject jo = (JsonObject) jsonParser.parse(jsonResult); JsonArray jsonArr = jo.getAsJsonArray("data"); Gson googleJson = new Gson(); ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class); System.out.println("Listas existentes en data : " + jsonObjList.size()); System.out.println("los elementos de la lista son : " + jsonObjList.toString()); String dataResult = jsonObjList.toString(); System.out.println("\n\n--------------------- EL OBJETO JSON ARRAY---------------------------\n\n"); /// jsonArr.remove(1); String elemento1 = null; Iterator<JsonElement> nombreIterator = jsonArr.iterator(); JsonElement elemento = null; while (nombreIterator.hasNext()) { elemento = nombreIterator.next(); System.out.print(elemento + " \n"); elemento1 = elemento.toString(); System.out.println("El elemento 1 es " + elemento1); } cData data = gson.fromJson(elemento1, cData.class); // Account account = gson.fromJson(jo, Account.class); if (data.getAccount().getFirst_name() == null) { System.out.println("Error"); } else { System.out.print(data.getAccount().getFirst_name()); } // System.out.println(data.acount.getNumber()); System.out.println("\n\n--------------------- OBTENEMOS EL OBJETO ACCOUNT---------------------------\n\n"); //JsonObject jObject = (JsonObject) jsonParser.parse(elemento1); // System.out.println(jObject.getAsJsonPrimitive("number")); }
From source file:galaxy_server.java
@Override public boolean sendFile(String filePath) throws Exception { String url = this.getHost() + "/api/histories/most_recently_used"; HashMap<String, String> params = new HashMap<>(); params.put("key", this.getApiKey()); String response = this.sendGet(url, params); JsonElement jelement = new JsonParser().parse(response); String historyID = jelement.getAsJsonObject().get("id").getAsString(); String charset = "UTF-8"; url = this.getHost() + "/api/tools/"; MultipartUtility multipart = new MultipartUtility(url, charset); multipart.addFormField("key", this.getApiKey()); multipart.addFormField("inputs", "{\"dbkey\":\"?\",\"file_type\":\"txt\",\"files_0|type\":\"upload_dataset\",\"files_0|space_to_tab\":null,\"files_0|to_posix_lines\":\"Yes\"}"); multipart.addFormField("tool_id", "upload1"); multipart.addFormField("history_id", historyID); multipart.addFilePart("files_0|file_data", new File(filePath)); multipart.finish();//from ww w .j a va 2s .c o m return true; }
From source file:CompanyController.java
public static Object getCompanyById(Request request, Response response, CompaniesEditor compEdit) { HttpURLConnection con = null; try {/* w ww.j ava 2s . c o m*/ int id = Integer.valueOf(request.params("id")); Company company = compEdit.get(id); if (company != null) { FinalJson json = new FinalJson(); String otherService = ""; try { String url = "http://owner:4321/people/" + id; URL obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response1 = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response1.append(inputLine); } in.close(); otherService = response1.toString(); JsonObject jsonObject = new JsonParser().parse(otherService).getAsJsonObject(); String ownerName = jsonObject.get("name").getAsString(); String ownerSurname = jsonObject.get("surname").getAsString(); String ownerGender = jsonObject.get("gender").getAsString(); String ownerAddress = jsonObject.get("address").getAsString(); json.ownerAddress = ownerAddress; json.ownerGender = ownerGender; json.ownerName = ownerName; json.ownerSurname = ownerSurname; json.id = company.getId(); json.city = company.getCity(); json.name = company.getName(); json.phoneNumber = company.getPhoneNumber(); return json; } catch (Exception e) { return company; } } else { response.status(404); throw new Exception("404. Failed to find company by id: " + id + "!"); } } catch (Exception e) { return e.getMessage(); } finally { if (con != null) { con.disconnect(); } } }
From source file:CBDocUtil.java
String prettyPrint(String uglyJSONString) { String prettyJsonString = uglyJSONString; try {//from w ww . ja v a 2 s . co m Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(uglyJSONString); prettyJsonString = gson.toJson(je); } catch (Exception e1) { logger.log(java.util.logging.Level.INFO, "Excepton {0} {1} ", new Object[] { e1.getMessage(), getPrintStackTrace(e1) }); } return prettyJsonString; }
From source file:RawCollectionsExample.java
License:Apache License
@SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) { Gson gson = new Gson(); Collection collection = new ArrayList(); collection.add("hello"); collection.add(5);/*from w ww. j a va 2 s . c om*/ collection.add(new Event("GREETINGS", "guest")); String json = gson.toJson(collection); System.out.println("Using Gson.toJson() on a raw collection: " + json); JsonParser parser = new JsonParser(); JsonArray array = parser.parse(json).getAsJsonArray(); String message = gson.fromJson(array.get(0), String.class); int number = gson.fromJson(array.get(1), int.class); Event event = gson.fromJson(array.get(2), Event.class); System.out.printf("Using Gson.fromJson() to get: %s, %d, %s", message, number, event); }
From source file:GeoLocation.java
public static void main(String args[]) { try {/*from ww w .j a v a 2 s . co m*/ URL myURL = new URL( "https://maps.googleapis.com/maps/api/geocode/json?latlng=17.451425,%2078.380957&key=AIzaSyDe_RBKl4DBGy6YCWRPXi9eQzYACt05Tr8"); URLConnection myURLConnection = myURL.openConnection(); myURLConnection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while ((line = in.readLine()) != null) { sb.append(line + "\n"); } JsonElement json = new JsonParser().parse(sb.toString()); JsonObject j = json.getAsJsonObject(); JsonElement je = j.get("results"); JsonArray ja = je.getAsJsonArray(); JsonElement je1 = ja.get(1); JsonObject j1 = je1.getAsJsonObject(); JsonElement je2 = j1.get("formatted_address"); System.out.println(je2.getAsString()); } catch (MalformedURLException e) { // new URL() failed // ... } catch (IOException e) { // openConnection() failed // ... } }
From source file:QuoteSetvlet.java
private JsonObject getJson(HttpServletRequest request) throws IOException, JsonSyntaxException { Scanner jsonScanner = new Scanner(request.getInputStream()); String json = ""; while (jsonScanner.hasNext()) { json += jsonScanner.nextLine();/*from www . j av a 2 s . c o m*/ } //Get the quote text from the provided Json JsonObject newQuote = new JsonParser().parse(json).getAsJsonObject(); return newQuote; }
From source file:RunnerRepository.java
License:Apache License
public static void parseIni(File ini) { try {//from w w w. j a v a 2 s .co m FileInputStream in = new FileInputStream(ini); InputStreamReader inputStreamReader = new InputStreamReader(in); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuffer b = new StringBuffer(""); String line; try { while ((line = bufferedReader.readLine()) != null) { b.append(line); } bufferedReader.close(); inputStreamReader.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } JsonElement jelement = new JsonParser().parse(b.toString()); inifile = jelement.getAsJsonObject(); editors = inifile.getAsJsonObject("editors"); looks = inifile.getAsJsonObject("looks"); layout = inifile.getAsJsonObject("layout"); plugins = inifile.getAsJsonArray("plugins"); if (layout == null) { inifile.add("layout", new JsonObject()); writeJSon(); layout = inifile.getAsJsonObject("layout"); } if (plugins == null) { inifile.add("plugins", new JsonArray()); writeJSon(); plugins = inifile.getAsJsonArray("plugins"); } } catch (Exception e) { System.out.print("Could not parse ini file: "); try { System.out.println(ini.getCanonicalPath()); } catch (Exception ex) { ex.printStackTrace(); } e.printStackTrace(); } }