Advertisement
Siliarus

JsonReader

Sep 2nd, 2015
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.90 KB | None | 0 0
  1. package package1;
  2. //Code from: http://stackoverflow.com/questions/4308554/simplest-way-to-read-json-from-a-url-in-java
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.Reader;
  8. import java.net.URL;
  9. import java.nio.charset.Charset;
  10.  
  11. import org.json.JSONException;
  12. import org.json.JSONObject;
  13.  
  14. public class JsonReader {
  15.  
  16.   private static String readAll(Reader rd) throws IOException {
  17.     StringBuilder sb = new StringBuilder();
  18.     int cp;
  19.     while ((cp = rd.read()) != -1) {
  20.       sb.append((char) cp);
  21.     }
  22.     return sb.toString();
  23.   }
  24.  
  25.   public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException, InterruptedException {
  26.     InputStream is = new URL(url).openStream();
  27.     try {
  28.       BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
  29.       String jsonText = readAll(rd);
  30.       JSONObject json = new JSONObject(jsonText);
  31.       return json;
  32.     } finally {
  33.       is.close();
  34.      
  35.     }
  36.   }
  37.  
  38.   public static String getFrom (String adress, String thing) throws IOException, JSONException {
  39.       String ret = "";
  40.      // System.out.println("Adresse: "+adress);
  41.       JSONObject json = null;
  42.     try {
  43.         json = readJsonFromUrl(adress);
  44.     } catch (InterruptedException e) {
  45.         // TODO Auto-generated catch block
  46.         e.printStackTrace();
  47.     }
  48.     //  System.out.println("Erfolgreich.");
  49.         ret = json.get(thing).toString();
  50.     //  System.out.println(ret);
  51.       return ret ;
  52.   }
  53.  
  54.   public static JSONObject getallFrom (String adress) throws IOException, JSONException {
  55.     //  System.out.println("Adresse: "+adress);
  56.       JSONObject json = null;
  57.     try {
  58.         json = readJsonFromUrl(adress);
  59.     } catch (InterruptedException e) {
  60.         // TODO Auto-generated catch block
  61.         e.printStackTrace();
  62.     }
  63.     //  System.out.println("Erfolgreich.");
  64.       return json ;
  65.   }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement