Solved Read a JSON from a web api

Discussion in 'Plugin Development' started by galaipa, Feb 26, 2015.

Thread Status:
Not open for further replies.
  1. @galaipa dont think this has much to do with bukkit. try stackoverflow.com there you will get faster help i guess
     
    galaipa likes this.
  2. Offline

    teej107

    galaipa likes this.
  3. Offline

    TGRHavoc

    Create a URL object with the URL that contains the JSON file.
    Create a BufferedReader (Using URL#openStream() inside of a InputStreamReader (I think))
    Create a String
    While ( (String = BufferedReader#readLine) != null)
    Do whatever (Add to a sting buffer maybe?)
    JSONParser#paser( String/String Buffer)
    Make sure to close the BufferedReader.
     
    galaipa likes this.
  4. @TGRHavoc Thank you. I have arrived here. But I get all the json file and I only need to get one value.

    Code:
    public String zerrendandago(String name){
    StringBuilder content = new StringBuilder();
    try
    {
    URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + name);
    URLConnection urlConnection = url.openConnection();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    String line;
    while ((line = bufferedReader.readLine()) != null)
    {
    content.append(line + "\n");
    }
    bufferedReader.close();
    }
    catch(Exception e)
    {
    e.printStackTrace();
    return null;
    }
    return content.toString();
    }
     
  5. Offline

    TGRHavoc

    JSONObject =(JSONObject) JSONParser#parse(String)
    And because JSONObject implements java.util.Map, you can just do JSONObject#get("VALUE")
     
    galaipa likes this.
  6. @TGRHavoc Thank you very much!
    I leave here the final code:
    Code:
    public String web(String name, String zer){
    StringBuilder content = new StringBuilder();
    try
    {
    URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + name);
    URLConnection urlConnection = url.openConnection();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    String line;
    while ((line = bufferedReader.readLine()) != null)
    {
    content.append(line + "\n");
    }
    bufferedReader.close();
    }
    catch(Exception e)
    {
    return null;
    }
    try{
    String lortu = content.toString();
    JSONParser parser = new JSONParser();
    JSONObject jo = (JSONObject) parser.parse(lortu);
    return (String) jo.get(zer);
    }
    catch(Exception e){
    return null;
    }
    }
     
  7. Offline

    TGRHavoc

    @galaipa
    No problem, glad you figured it out :)
    Don't forget to mark this thread as "Solved"
     
    galaipa likes this.
Thread Status:
Not open for further replies.

Share This Page