Peril Peril - 1 year ago 154
JSON Question

Parsing JSON from URL

Is there any simplest way to parse JSON from a URL? I used Gson I can't find any helpful examples.

Answer Source
  1. First you need to download the URL (as text):

    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 = != -1)
                buffer.append(chars, 0, read); 
            return buffer.toString();
        } finally {
            if (reader != null)
  2. Then you need to parse it (and here you have some options).

    • GSON (full example):

      static class Item {
          String title;
          String link;
          String description;
      static class Page {
          String title;
          String link;
          String description;
          String language;
          List<Item> items;
      public static void main(String[] args) throws Exception {
          String json = readUrl(""
                                + "dhtmltutors/javascriptkit.json");
          Gson gson = new Gson();        
          Page page = gson.fromJson(json, Page.class);
          for (Item item : page.items)
              System.out.println("    " + item.title);

          Document Text Resizer
          JavaScript Reference- Keyboard/ Mouse Buttons Events
          Dynamically loading an external JavaScript or CSS file
    • Try the java API from

      try {
          JSONObject json = new JSONObject(readUrl("..."));
          String title = (String) json.get("title");
      } catch (JSONException e) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download