从 URL 解析 JSON

新手上路,请多包涵

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

原文由 Peril 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 953
2 个回答
  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
    
    
    
      try {
         JSONObject json = new JSONObject(readUrl("..."));
    
    
         String title = (String) json.get("title");
         ...
    
    
     } catch (JSONException e) {
         e.printStackTrace();
     }
    
    
    

原文由 dacwe 发布,翻译遵循 CC BY-SA 3.0 许可协议

GSON 有一个带有 Reader 对象的构建器: fromJson(Reader json, Class classOfT)

这意味着您可以从 URL 创建一个 Reader,然后将其传递给 Gson 以使用流并进行反序列化。

只有 三行 相关代码。

 import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;

import com.google.gson.Gson;

public class GsonFetchNetworkJson {

    public static void main(String[] ignored) throws Exception {

        URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
        InputStreamReader reader = new InputStreamReader(url.openStream());
        MyDto dto = new Gson().fromJson(reader, MyDto.class);

        // using the deserialized object
        System.out.println(dto.headers);
        System.out.println(dto.args);
        System.out.println(dto.origin);
        System.out.println(dto.url);
    }

    private class MyDto {
        Map<String, String> headers;
        Map<String, String> args;
        String origin;
        String url;
    }
}

如果您碰巧收到 403 错误代码,并且端点在其他方面工作正常(例如使用 curl 或其他客户端),那么可能的原因可能是端点需要一个 User-Agent 标头和默认情况下 Java URLConnection 没有设置它。一个简单的解决方法是在文件顶部添加例如 System.setProperty("http.agent", "Netscape 1.0");

原文由 ccpizza 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏