返回JSON数据到客户端

时间:2022-02-13 19:27:36

1)、使用xml数据格式返回给安卓系统进行解析是十分耗费性能,一般使用JSON数据格式会对程序的优化起到十分好的作用。在客户端请求服务器的地址后面加上一个参数format=json

2)、首先对web应用进行修改,改名为jsonVideoNews,在srvlet当中首先判断用户请求的参数是否为json,如果是,返回json格式,如果不是,返回xml格式的数据。

3)、json数据的一般格式

[{id:80,title=”捉妖记”,timelength=129},{},{}],使用StringBuilder进行构造,首先一头一尾的[]加上,append(‘[’),接着对集合数据进行迭代,迭代结束,需要删除最后一个逗号,调用API deleteCharAt(builder.length-1);最后将数据转发给一个新的jspjsonvideonews.jsp

使用EL表达式放在页面中,由于json格式属于普通文本类型,将内容类型修改成plain

4)、新建安卓工程,jsonNews,并在其中创建一个方法用来解析json格式的数据,采用JSONArray对象来完成解析。

返回JSON数据到客户端

关键源代码:

服务器端:

public List getLatestNews(){
List list=new ArrayList();
list.add(new News(1, "纳妾记", 45));
list.add(new News(2, "花千骨", 40));
list.add(new News(3, "捉妖记", 120));
list.add(new News(4, "天涯明月刀", 50));
list.add(new News(5, "仙剑客栈", 25));
return list;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//[{id:80,title=”捉妖记”,timelength=129},{},{}]
Listdata=service.getLatestNews();
String format=(String) request.getParameter("format");
if(format.equals("json")){
StringBuilder builder=new StringBuilder();
builder.append('[');
for(News news:data){
builder.append('{');
builder.append("id:").append(news.getId()).append(',');
builder.append("title=").append("\"").append(news.getTitle()).append("\",");
builder.append("timelength=").append(news.getTimelength());
builder.append('}').append(',');
}
builder.deleteCharAt(builder.length()-1);
builder.append(']');
request.setAttribute("json", builder);
RequestDispatcher dispatcherjson=request.getRequestDispatcher("/WEB-INF/page/jsonvideonews.jsp");
dispatcherjson.forward(request, response);
}else{
request.setAttribute("video", data);
RequestDispatcher dispatcher=request.getRequestDispatcher("/WEB-INF/page/videonews.jsp");
dispatcher.forward(request, response);
}
}
安卓端:private List parserJSON(InputStream inputStream) throws IOException, JSONException {List list=new ArrayList();byte[] b=Read(inputStream);String json=new String(b);JSONArray array=new JSONArray(json);for(int i=0;iJSONObject jsonObject=array.getJSONObject(i);News news=new News(jsonObject.getInt("id"), jsonObject.getString("title"), jsonObject.getInt("timelength"));list.add(news); }return list;}private byte[] Read(InputStream inputStream) throws IOException {byte[] data=new byte[1024];ByteArrayOutputStream outputStream=new ByteArrayOutputStream();int len=0;while((len=inputStream.read(data))>0){outputStream.write(data, 0, len);}inputStream.close();outputStream.close();byte[] result=outputStream.toByteArray();return result;}public class mHandler extends Handler {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 0:{Listcontent=(List) msg.obj;List> item=new ArrayList>();for(News news:content){HashMap map=new HashMap();map.put("title", news.getTitle());map.put("timelength", news.getTimelength());item.add(map);}SimpleAdapter adapter=new SimpleAdapter(getApplicationContext(),item,R.layout.items,new String[]{"title","timelength"},new int[]{R.id.title,R.id.timelength});listView.setAdapter(adapter);break;}case 1:{Toast.makeText(getApplicationContext(), "未找到信息", Toast.LENGTH_LONG).show();break;}}}}