从 URL 解析 JSON [英] Parsing JSON from URL

查看:40
本文介绍了从 URL 解析 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有最简单的方法可以从 URL 解析 JSON?我使用了 Gson,但找不到任何有用的示例.

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

推荐答案

  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();
    }
}

  • 然后你需要解析它(这里你有一些选择).

    • 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 the java API from json.org:

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

  • 这篇关于从 URL 解析 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆