日期:2014-05-16  浏览次数:20376 次

Android学习笔记---26_采用JSON格式返回数据给资讯客户端,效率上要高于xml文件解析和传输
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("},");
}