栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从URL解析JSON

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从URL解析JSON

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/373649.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号