返回JSON數據到客戶端

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對象來完成解析。



關鍵源代碼:

服務器端:

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;i
JSONObject 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 {

@Override
public 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;
}
}
}

}

發佈了42 篇原創文章 · 獲贊 31 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章