java - 从 URL 解析 JSON

标签 java json url

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

最佳答案

  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();
        }
    }
    
  2. 然后你需要解析它(这里有一些选项)。

    • 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 试用 java API :

      try {
          JSONObject json = new JSONObject(readUrl("..."));
      
          String title = (String) json.get("title");
          ...
      
      } catch (JSONException e) {
          e.printStackTrace();
      }
      

关于java - 从 URL 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7467568/

相关文章:

java - 如何在我的 Java 应用程序中查找内存泄漏

javascript - Highcharts 生成不正确

java - 从文本文件获取输入并返回 json 字符串的程序

c# - 打开网站错误

java - 如何使用 Java 代码为 iOS 创建钛移动模块?

java - 使 Spring Boot/actuator/heath 并行运行检查

javascript - 在 GWT (JSNI) 中将字符串转换为 JSON 对象

url - 在 golang http.NewRequest 中包含 %2F

c# - 没有尾部斜杠的基本 Uri

java - 需要 Java regEx 来读取字符串中的数字