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