Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

Android学习笔记---26_采用JSON格式返回数据给资讯客户端,效率上要高于xml文件解析和传输

$
0
0
2013-03-22
26_采用JSON格式返回数据给资讯客户端
----------------------------------------
1.因为在android中,使用xml格式传输数据的话,性能是十分低的.
2.使用json进行传输数据,要比使用xml文件传输数据,性能要好一些
-------------------------------------------------------------
3.需求,如果用户在路径后面加上了后缀,就返回json的数据,给android客户端,如果没有加后 


 缀,那么就返回xml的数据,给android客户端
  原来的路径是:http://192.168.1.110:6118/VideoNews/ListServlet
  加上后缀的路径是:http://127.0.0.1:6118/VideoNews/ListServlet?format=json
-----------------------------------------------------------------------------
4.一下是实现使用json进行数据进行传输的所有源代码
a.服务器,返回json数据
  在VideoNewsTest这个web项目中:
  /VideoNewsTest/src/com/credram/servlet/ListServlet.java
package com.credram.servlet;


import java.io.IOException;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.credream.entity.News;
import com.credream.service.VideoNewsService;
import com.credream.service.impl.VideoNewsServiceImpl;


/**
 * Servlet implementation class ListServlet
 */
public class ListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
       
 

private VideoNewsService service=new VideoNewsServiceImpl();
    public ListServlet() {
 
       
    }


/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 


response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse 


response) throws ServletException, IOException {
doPost(request, response);
}


/**
* @see HttpServlet#doPost(HttpServletRequest request, 


HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse 


response) throws ServletException, IOException {
List<News> videos=service.getLastNews();
String format=request.getParameter("format");
if("json".equals(format)){
//json:数据的样子[],在js语法中[]代表数组
//在[]中构造对象:
//[{id:56,title:"xiaofeng",timelength:90},


{id:36,title:"xiaofeng",timelength:90}]
StringBuilder builder=new StringBuilder();
builder.append("[");
for(News news:videos){
builder.append("{");
builder.append("id:").append(news.getId()).append(",");
builder.append("title:\"").append(news.getTitle


()).append("\",");
builder.append("timelength:").append(news.getTimelength


());
builder.append("},");
}
builder.deleteCharAt(builder.length()-1);
builder.append("]");
request.setAttribute("json", builder.toString());
request.getRequestDispatcher("/WEB-


INF/page/jsonvideosnews.jsp").forward(request, response);
}else{
request.setAttribute("videos", videos);
request.getRequestDispatcher("/WEB-


INF/page/videosnews.jsp").forward(request, response);
}
}


}
-----------------------------------------------------------
这个servlet的作用:当用户访问带参数的地址:
http://127.0.0.1:6118/VideoNews/ListServlet?format=json
将返回json数据,当用户访问地址:http://192.168.1.110:6118/VideoNews/ListServlet
时返回的是xml数据
-----------------------------------------------------
b.在android项目中:
  /GetNetNews/src/com/credream/service/VideoNewsService.java
文件中添加对json数据的解析方法:
 /**
* 获取解析后的json数据,返回list
* @return
* @throws Exception
*/
public static  List<News> getJSONLastNews()throws Exception{
String path="http://192.168.1.110:6118/VideoNews/ListServlet?


format=json";
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode()==200){
InputStream inStream=conn.getInputStream();
return parseJSON(inStream);
}
return null;
}
-----------------------------------------------------------------
c.这里用到了以前写的一个工具类,可以把传入的数据流,以byte[]的形式返回  在netimage  


项目中拷贝/netimage/src/com/credream/util/StreamTool.java出来,到GetNetNews项目  


中(本项目)
----------------------------------------
  
d.解析json的方法:
  /**
* 解析json数据
* @param inStream
* @return
*/
private static List<News> parseJSON(InputStream inStream)
throws Exception{
List<News> newes=new ArrayList<News>();
byte[] data=StreamTool.read(inStream);
//服务器返回的字符串,是文本数据
String json=new String(data);//把data转换成,字符串
//把json字符串转换成数组对象
JSONArray array=new JSONArray(json);
for(int i=0;i<array.length();i++){
//[{id:56,title:"xiaofeng",timelength:90},{id:36,title:"xiaofeng",timelength:90}]
//一个大括号就是一个json对象
JSONObject jsonObject=array.getJSONObject(i);//得到第i个json;
int id=jsonObject.getInt("id");
String title=jsonObject.getString("title");
int timelength= jsonObject.getInt("timelength");
News news=new News(id, title, timelength);
newes.add(news);
}
return newes;
}
---------------------------------------------------------------------------
作者:lidew521 发表于2013-3-23 0:09:14 原文链接
阅读:116 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>