小编典典

从URL解析JSON

json

有没有最简单的方法来从URL解析JSON?我使用Gson找不到任何有用的示例。


阅读 232

收藏
2020-07-27

共1个答案

小编典典

  1. 首先,您需要下载URL(作为文本):
        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();
        }
    }
  1. 然后您需要解析它(这里有一些选项)。

    • GSON(完整示例):
                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("http://www.javascriptkit.com/"
                                  + "dhtmltutors/javascriptkit.json");

            Gson gson = new Gson();        
            Page page = gson.fromJson(json, Page.class);

            System.out.println(page.title);
            for (Item item : page.items)
                System.out.println("    " + item.title);
        }

输出:

                javascriptkit.com
            Document Text Resizer
            JavaScript Reference- Keyboard/ Mouse Buttons Events
            Dynamically loading an external JavaScript or CSS file
* **试试[ json.org上](http://json.org/java)的Java API :**
                try {
            JSONObject json = new JSONObject(readUrl("..."));

            String title = (String) json.get("title");
            ...

        } catch (JSONException e) {
            e.printStackTrace();
        }
2020-07-27