java通过url得到json字符串并解析
来源:互联网 发布:sistar shake it 编辑:程序博客网 时间:2024/06/05 06:48
c/s架构中进场用到通过url得到json字符串,例如android
这种方式可以方便url获得json字符串
@Testpublic void test0(){StringBuffer sb = new StringBuffer();try {URL url = new URL("http://localhost:3000/news/getById?id=186208");InputStreamReader isr = new InputStreamReader(url.openStream());char[] buffer = new char[10];while(isr.read(buffer)!=-1){sb.append(buffer);}System.out.println(sb.toString());} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
但是,这样得到的字符串是有问题的,常常在末尾莫名的多加了几个字符。例如:
目的字符串:
{
"id": "",
"title": "北京军区为集宁义务植树基地再添新绿",
"date": "2014-04-28T09:25:13.000Z",
"author": "首席记者 乌云夫"
}席记者 乌云夫
在最后的花括号结束后就没有字符了,但是最后获得的确多了几个字符,
这是因为在将buffer这个缓存字符数组增加到StringBuffer上时没有确定当前获取的字符长度,最后读取的字符长度可能没有这个buffer缓存数组长,所以将上一次的字符又添加到了StringBuffer的末尾。
解决方法:
在每次将数据读到缓存数组buffer中时,检查当前读取的字符长度,将缓存数组增加到StringBuffer时,按照字符数组长度增加
@Testpublic void test1() {String json = null;StringBuffer sb = new StringBuffer();try {URL url = new URL("http://localhost:3000/news/getById?id=186208");InputStreamReader isr = new InputStreamReader(url.openStream());char[] buffer = new char[1024];<span style="color: rgb(255, 0, 0);">int len = 0;while((len=isr.read(buffer))!=-1){sb.append(buffer,0,len);}</span>} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}json = sb.toString();System.out.println(json);}
对返回的json数据进行解析JSONTokener jsonParser = new JSONTokener(json);JSONObject article = (JSONObject) jsonParser.nextValue();String title = article.getString("title");System.out.println(title);
其中JSONTokener所在的包 net.sf.json.util
maven中获取json-lib.jar
<span style="white-space:pre"></span><dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.3</version> <classifier>jdk15</classifier></dependency>
0 0
- java通过url得到json字符串并解析
- java通过url请求服务器端json数据并解析成想要的数据
- java直接访问链接url,并对返回的json字符串进行解析
- PHP解析URL并得到URL中的参数
- PHP解析URL并得到URL中的参数
- PHP解析URL并得到URL中的参数
- PHP解析URL并得到URL中的参数
- php解析url并得到url中的参数
- php解析url并得到url中的参数
- php解析url并得到url中的参数
- JS 解析JSON字符串 得到对象数组
- ASP.net 解析 JSON字符串得到数组
- java获取手机端JSON数据 并解析为字符串
- Java json按照字符串顺序解析,并逆向读取
- 通过URL获取JSON解析详解
- 通过URL建立连接 然后解析json
- Android-通过URL获取网络资源 Json 字符串
- URL请求并解析JSON数据
- git和github菜鸟使用步骤
- Eclipse设置不格式化注释
- 解决ubuntu中mysql数据库表名不能为中文,以及插入中文乱码问题
- C#5.0 使用async轻松解决跨线程访问UI
- JVM中ClassLoader的工作机制
- java通过url得到json字符串并解析
- nand flash 的oob 及坏块管理
- VAssistX破解办法和用处
- upstream均衡负载模块(一)加权轮询策略
- TCP状态转换图
- RMI和Socket的比较及区别(转)
- 多态中成员变量与成员方法的调用
- [Information Security] Cracking Vignere Code
- Unity3D ITween!