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

查看:88
本文介绍了从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

  • 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天全站免登陆