List of usage examples for com.google.gson JsonParser parse
@Deprecated public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException
From source file:com.devamatre.core.JSONHelper.java
License:Open Source License
/** * //from www .j a va 2 s . c om * @param jsonString * @return */ public static JsonElement jsonElement(String jsonString) { JsonParser jsonParser = new JsonParser(); return jsonParser.parse(jsonString); }
From source file:com.devamatre.core.JSONHelper.java
License:Open Source License
/** * //from www . j a v a 2s .c o m * @param jsonString * @return */ public static boolean isValidJSONString(String jsonString) { if (jsonString == null) { return false; } else { JsonParser parser = new JsonParser(); try { parser.parse(jsonString); } catch (JsonSyntaxException ex) { return false; } return true; } }
From source file:com.devbliss.doctest.utils.JSONHelper.java
License:Apache License
/** * //from ww w. ja v a 2 s . c om * Pretty prints any json input. * * @param json * @return */ public String prettyPrintJson(String json) { if (!isJsonValid(json)) { return json; } Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(json); String returnvalue = gson.toJson(je); return returnvalue; }
From source file:com.devonfw.module.i18n.common.util.I18nUtils.java
License:Apache License
/** * @param resourceMap contains the resources in the form of key value pairs * @param filter received from service//from w w w. ja v a2s. c om * @return resources as JSON String * @throws Throwable thrown by getResourcesAsJSON */ public static String getResourcesAsJSON(HashMap<String, String> resourceMap, String filter) throws Throwable { JsonParser jsonParser = new JsonParser(); final java.lang.reflect.Type mapType = new TypeToken<Map<String, String>>() { }.getType(); String strJSON = new GsonBuilder().registerTypeAdapter(mapType, new BundleMapSerializer()).create() .toJson(resourceMap, mapType); if (filter != null && !filter.isEmpty()) { JsonObject obj = (JsonObject) jsonParser.parse(strJSON); strJSON = I18nUtils.getJsonObj(obj, filter); } return strJSON; }
From source file:com.discord.bot.BingHandler.java
public String bingSearch(String searchQuery) { String link = ""; try {//from w w w .ja v a2 s . com final String bingUrlPattern = "https://api.datamarket.azure.com/Bing/Search/Image?Query=%%27%s%%27&$format=JSON&Adult=%%27Off%%27"; final String query = URLEncoder.encode(searchQuery, StandardCharsets.UTF_8.name()); final String bingUrl = String.format(bingUrlPattern, query); final String accountKeyEnc = Base64.getEncoder() .encodeToString((AuthVariables.ACCOUNTKEY + ":" + AuthVariables.ACCOUNTKEY).getBytes()); final URL url = new URL(bingUrl); final URLConnection connection1 = url.openConnection(); connection1.setRequestProperty("Authorization", "Basic " + accountKeyEnc); try (final BufferedReader in = new BufferedReader( new InputStreamReader(connection1.getInputStream()))) { String inputLine; final StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } try { JsonParser jsonParser = new JsonParser(); int size = jsonParser.parse(response.toString()).getAsJsonObject().getAsJsonObject("d") .getAsJsonObject().getAsJsonArray("results").size(); if (size > 0) { Random r = new Random(); int choice = r.nextInt(size); JsonObject searchInfo = jsonParser.parse(response.toString()).getAsJsonObject() .getAsJsonObject("d").getAsJsonObject().getAsJsonArray("results").get(choice) .getAsJsonObject(); link = searchInfo.get("MediaUrl").getAsString(); link += " " + searchInfo.get("Title").getAsString(); } } catch (JsonSyntaxException | java.lang.IndexOutOfBoundsException e) { return ""; } } } catch (MalformedURLException ex) { Logger.getLogger(BingHandler.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException e) { Logger.getLogger(BingHandler.class.getName()).log(Level.SEVERE, null, e); } return link; }
From source file:com.discord.bot.ImgurHandler.java
public String randomImgur() { String json = ""; String message = ""; try {/*from w w w .j ava2 s . c o m*/ Random r = new Random(); int randomPage = 1 + r.nextInt(4); ZonedDateTime timeNow = ZonedDateTime.now(); if (lastImgurCall == null || lastImgurCall.compareTo(timeNow.minusMinutes(TIMELIMIT)) <= 0 || randomImgurNumbers.size() >= IMGURLIMIT) { String url = "https://api.imgur.com/3/gallery/random/random/" + Integer.toString(randomPage); json = Bot.readAuthUrl(url); // There are 5 random imgur sites. For some reason, some of them are sometimes empty. // Lets get the first one thats not empty. for (int i = 0; json.isEmpty() || i == 5; i++) { randomPage = 1 + r.nextInt(4); url = "https://api.imgur.com/3/gallery/random/random/" + Integer.toString(randomPage); json = Bot.readAuthUrl(url); } lastImgurCall = ZonedDateTime.now(); if (randomImgurNumbers.size() >= IMGURLIMIT) { randomImgurNumbers.clear(); } } int choice = 1 + r.nextInt(49); while (randomImgurNumbers.contains(choice)) { choice = 1 + r.nextInt(49); } if (!randomImgurNumbers.contains(choice)) { randomImgurNumbers.add(choice); } JsonParser jsonParser = new JsonParser(); JsonObject imgurInfo = jsonParser.parse(json).getAsJsonObject().getAsJsonArray("data").get(choice) .getAsJsonObject(); String link = imgurInfo.get("link").getAsString(); String title = imgurInfo.get("title").getAsString(); message = link + " " + title; } catch (Exception ex) { Logger.getLogger(ImgurHandler.class.getName()).log(Level.SEVERE, null, ex); } return message; }
From source file:com.discord.bot.ImgurHandler.java
public String randomSubredditImgur(String subreddit) { String json = ""; String message = ""; try {// w w w .j av a 2 s . c o m String url = "https://api.imgur.com/3/gallery/r/" + subreddit; json = Bot.readAuthUrl(url); if (!json.isEmpty()) { JsonParser jsonParser = new JsonParser(); int size = jsonParser.parse(json).getAsJsonObject().getAsJsonArray("data").size(); if (size > 0) { Random r = new Random(); int randomPage = r.nextInt(size); JsonObject imgurInfo = jsonParser.parse(json).getAsJsonObject().getAsJsonArray("data") .get(randomPage).getAsJsonObject(); String link = ""; if (imgurInfo.get("type").getAsString().equals("image/gif")) { link = imgurInfo.get("gifv").getAsString(); } else { link = imgurInfo.get("link").getAsString(); } String title = imgurInfo.get("title").getAsString(); if (!link.isEmpty() && !title.isEmpty()) { message = link + " " + title; } else if (!link.isEmpty()) { message = link; } } } } catch (Exception ex) { Logger.getLogger(ImgurHandler.class.getName()).log(Level.SEVERE, null, ex); } return message; }
From source file:com.drguildo.bm.BookmarksManager.java
License:Open Source License
public static Bookmarks load() throws IOException { StringBuilder stringBuilder = new StringBuilder(); if (!Files.exists(bookmarkPath)) { return bookmarks; }// w w w . j a v a 2s .c o m try { BufferedReader bufferedReader = new BufferedReader(new FileReader(bookmarkFile)); String string = bufferedReader.readLine(); while (string != null) { stringBuilder.append(string); string = bufferedReader.readLine(); } bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); throw new IOException(e); } if (stringBuilder.length() == 0) { return bookmarks; } String json = stringBuilder.toString(); JsonParser parser = new JsonParser(); JsonArray array = parser.parse(json).getAsJsonArray(); for (JsonElement element : array) { JsonObject jsonObject = element.getAsJsonObject(); URL url = new URL(jsonObject.get("url").getAsString()); Tags tags = new Tags(); for (JsonElement tagElement : jsonObject.get("tags").getAsJsonArray()) { tags.add(tagElement.getAsString()); } Date date = new Date(jsonObject.get("added").getAsLong()); bookmarks.add(new Bookmark(url, tags, date)); } return bookmarks; }
From source file:com.edgytech.umongo.DocView.java
License:Apache License
String getTextForNode(Object obj, boolean indent) throws IOException { DBObject doc = null;// w ww . java2 s.c o m if (obj instanceof DBObject) { doc = (DBObject) obj; } else if (obj instanceof TreeNodeDocumentField) { doc = (DBObject) ((TreeNodeDocumentField) obj).getValue(); } else if (obj instanceof TreeNodeDocument) { doc = ((TreeNodeDocument) obj).getDBObject(); } if (doc == null) { return ""; } final DocumentSerializer ds = new DocumentSerializer(DocumentSerializer.Format.JSON, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); ds.setOutputStream(baos); try { ds.writeObject(doc); } finally { ds.close(); } String txt = new String(baos.toByteArray()); if (indent) { Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(txt); txt = gson.toJson(je); // add newline in case there are following docs txt += "\n"; } return txt; }
From source file:com.elevenpaths.latch.LatchAuth.java
License:Open Source License
/** * Makes an HTTP request//from w ww . j a va 2s . co m * @param URL The request URL. * @param method The request method. * @param headers Headers to add to the HTTP request. * @param data Parameters to add to the HTTP request body. * @return The server's JSON response or null if something has gone wrong. */ private JsonElement HTTP(String URL, String method, Map<String, String> headers, Map<String, String> data) { JsonElement rv = null; InputStream is = null; OutputStream os = null; InputStreamReader isr = null; try { URL theURL = new URL(URL); HttpURLConnection theConnection = (HttpURLConnection) theURL.openConnection(); theConnection.setRequestMethod(method); if (headers != null && !headers.isEmpty()) { Iterator<String> iterator = headers.keySet().iterator(); while (iterator.hasNext()) { String headerName = iterator.next(); theConnection.setRequestProperty(headerName, headers.get(headerName)); } } if (!(HTTP_METHOD_GET.equals(method) || HTTP_METHOD_DELETE.equals(method))) { StringBuilder sb = new StringBuilder(); if (data != null && !data.isEmpty()) { String[] paramNames = new String[data.size()]; data.keySet().toArray(paramNames); for (int i = 0; i < paramNames.length; i++) { sb.append(URLEncoder.encode(paramNames[i], CHARSET_UTF_8)); sb.append(LatchAuth.PARAM_VALUE_SEPARATOR); sb.append(URLEncoder.encode(data.get(paramNames[i]), CHARSET_UTF_8)); if (i < paramNames.length - 1) { sb.append(PARAM_SEPARATOR); } } } byte[] body = sb.toString().getBytes(CHARSET_ASCII); theConnection.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, HTTP_HEADER_CONTENT_TYPE_FORM_URLENCODED); theConnection.setRequestProperty(HTTP_HEADER_CONTENT_LENGTH, String.valueOf(body.length)); theConnection.setDoOutput(true); os = theConnection.getOutputStream(); os.write(body); os.flush(); } JsonParser parser = new JsonParser(); is = theConnection.getInputStream(); isr = new InputStreamReader(is, CHARSET_UTF_8); rv = parser.parse(isr); } catch (MalformedURLException e) { System.err.println("The URL is malformed (" + URL + ")"); e.printStackTrace(); } catch (IOException e) { System.err.println("An exception has been thrown when communicating with Latch backend"); e.printStackTrace(); } finally { if (os != null) { try { os.close(); } catch (IOException e) { System.err.println("An exception has been thrown when trying to close the output stream"); e.printStackTrace(); } } if (isr != null) { try { isr.close(); } catch (IOException e) { System.err.println("An exception has been thrown when trying to close the input stream reader"); e.printStackTrace(); } } if (is != null) { try { is.close(); } catch (IOException e) { System.err.println("An exception has been thrown when trying to close the input stream"); e.printStackTrace(); } } } return rv; }