Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class JSONParser {
- public static void main(String args[]) throws IOException {
- System.out.println("Enter Stock Symbol: ");
- String stockSymbol = new String(new BufferedReader(
- new InputStreamReader(System.in)).readLine());
- String jsonString = jsonURLToString(stockSymbolToURL(stockSymbol));
- System.out.println(getJsonKeyValue(jsonString, "change"));
- }
- static String jsonURLToString(String urlString) throws IOException {
- URL url = new URL(urlString);
- HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
- if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
- String jsonString = new BufferedReader(new InputStreamReader(
- url.openStream())).readLine().toString();
- return jsonString.trim();
- } else {
- return "Could not connect";
- }
- }
- static String stockSymbolToURL(String stockSymbol) {
- String urlString = "http://query.yahooapis.com/v1/public/yql?"
- + "q=select%20*%20from%20yahoo.finance.quote%20where%20"
- + "symbol%20in%20(%22" + stockSymbol
- + "%22)&format=json&diagnostics=t"
- + "rue&env=store%3A%2F%2Fdatatables.org%2Falltableswith"
- + "keys&callback=";
- return urlString;
- }
- static String getJsonKeyValue(String jsonString, String key) {
- String errorMessage = "getJsonArray: first argument does not contain second argument";
- String jsonValue = new String("");
- if (jsonString.contains(key)) {
- for (int i = 0; i < jsonString.length() - 1; i++) {
- if (jsonString.charAt(i) == '\"') {
- if (jsonString.substring(i + 1, i + key.length() + 1)
- .equalsIgnoreCase(key)) {
- i += key.length() + 1;
- if (jsonString.charAt(i) == '\"') {
- i += 3;
- while (jsonString.charAt(i) != '\"') {
- jsonValue += jsonString.charAt(i);
- i++;
- }
- }
- return jsonValue;
- }
- }
- }
- return jsonValue;
- } else {
- return errorMessage;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement