Get information from JSON at url

Discussion in 'Plugin Development' started by PRiiSM, Mar 16, 2015.

Thread Status:
Not open for further replies.
  1. Offline

    PRiiSM

  2. Offline

    ColonelHedgehog

    It sounds like you're looking for GSON. ;)
     
  3. I'd use json-simple for this, but others may use GSON, etc.

    Code to get information from URL:
    Code:
    private static String readUrl(String urlString) throws Exception {
        BufferedReader reader = null;
        try {
            URL url = new URL(urlString);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1) buffer.append(chars, 0, read);
            return buffer.toString();
        } finally {
            if (reader != null) reader.close();
        }
    }
    
    I did not write this and so I will not explain it, but yeah, it's pretty self explanatory unless you really don't understand streams and readers.

    The following requires json-simple but I think it comes with Bukkit. If not, it'll have to be included in the plugin JAR. Remember, there are alternative methods.
    Code:
    private static JSONParser jsonParser = new JSONParser();
    
    public int getViewers(String username) {
        try {
          String userData = readUrl("https://api.twitch.tv/kraken/search/streams?limit=10&offset=0&q=%5B" + username + "%5D"); // Read the URL and get the data as a String.
          Object parsedData = jsonParser.parse(userData); // Use the JSON parser to parse the information into an Object.
          if (parsedData instanceof JSONObject) { // If the parsed information is a Map (in the format of JSON), continue.
             JSONObject jsonData = (JSONObject) parsedData; // Convert the information into a JSON map (JSONObject is a Map).
             return jsonData.containsKey("viewers") ? Integer.parseInt(jsonData.get("viewers").toString()) : 0; // If the Map contains "viewers", parse it and return it, if not, return 0.
          }
       } catch (Exception ex) {
          ex.printStackTrace();
       }
       return 0;
    }
    
    I haven't used JSON in a fairly long time and so I have no idea if this'll work.
     
  4. Offline

    PRiiSM

    KingFaris11, first of all thank you!
    But it doesn't work, it's return 0 everytime :/
     
  5. That probably means the object isn't an instanceof Object, or viewers doesn't exist in the Map. Probably the first one, I'll check why after school unless someone replies before-hand.
     
  6. Offline

    SuchSwegMuchWow

  7. "The Justin.tv website, mobile apps, and APIs are no longer in service."

    I checked, and the reason is two things, firstly because I'm using:
    https://api.twitch.tv/kraken/search/streams?limit=10&offset=0&q=[DerJona]
    ^ Link.
    This returns a Map that doesn't contain "viewers":
    Send me the link for actually getting what you received, i.e.
    Secondly, "streams" is the actual Array that contains the Map for viewers, so I'll modify the code now.

    Finally, this won't fix the error, the above will, but make sure you call this asynchronously as this reads data from a URL, freezing the thread temporarily.

    Edit:
    Final code:
    Code:
    private static JSONParser jsonParser = new JSONParser();
    
    public static int getViewers(String username) {
        try {
            String userData = readUrl("https://api.twitch.tv/kraken/streams?channel=" + username); // Read the URL and get the data as a String.
            Object parsedData = jsonParser.parse(userData); // Use the JSON parser to parse the information into an Object.
            if (parsedData instanceof JSONObject) { // If the parsed information is a Map (in the format of JSON), continue.
                JSONObject jsonData = (JSONObject) parsedData; // Convert the information into a JSON map (JSONObject is a Map).
                if (jsonData.containsKey("streams")) { // If the Map contains 'streams'.
                    JSONArray streamArray = (JSONArray) jsonData.get("streams"); // Get the array of streams.
                    if (!streamArray.isEmpty()) { // If the streams array list is not empty.
                        JSONObject jsonMap = (JSONObject) streamArray.get(0); // Get the first Map in the array of streams. This is hardcoded unfortunately.
                        return jsonMap.containsKey("viewers") ? Integer.parseInt(jsonMap.get("viewers").toString()) : 0; // If the Map contains "viewers", parse it and return it, if not, return 0.
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return 0;
    }
    
    private static String readUrl(String urlString) throws Exception {
        BufferedReader reader = null;
        try {
            URL url = new URL(urlString);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1) buffer.append(chars, 0, read);
            return buffer.toString();
        } finally {
            if (reader != null) reader.close();
        }
    }
    
    You can do safety checks here like I did the first time, checking if each Object returned is an instanceof <x>, e.g. If 'streamers' was an instance of JSONArray, but it's not required.
     
    Last edited: Mar 17, 2015
Thread Status:
Not open for further replies.

Share This Page