為要獲取網絡上的json所以需要服務器端提供的支持。
一、創建服務器端:
服務器端項目結構:
服務器端運行效果圖:
第一步:創建業務所需的javabean
package com.jph.sj.model;
import java.util.date;
/**
* 新聞實體類
* @author jph
* date:2014.09.26
*/
public class news {
private integer id;
private string title;
private date publishdate;
public news(integer id, string title, date publishdate) {
this.id = id;
this.title = title;
this.publishdate = publishdate;
}
public integer getid() {
return id;
}
public void setid(integer id) {
this.id = id;
}
public string gettitle() {
return title;
}
public void settitle(string title) {
this.title = title;
}
public date getpublishdate() {
return publishdate;
}
public void setpublishdate(date publishdate) {
this.publishdate = publishdate;
}
}
第二步:創建業務邏輯接口和具體實現類
業務接口:
package com.jph.sj.service;
import java.util.list;
import com.jph.sj.model.news;
public interface newsservice {
/**
* 獲取最新的資訊
* @return
*/
public list<news> getlastnews();
}
業務接口的實現類:
package com.jph.sj.service.impl;
import java.util.arraylist;
import java.util.date;
import java.util.list;
import com.jph.sj.model.news;
import com.jph.sj.service.newsservice;
public class newsservicebean implements newsservice {
/**
* 獲取最新的視頻資訊
* @return
*/
public list<news> getlastnews(){
list<news> newes = new arraylist<news>();
newes.add(new news(1, "李白", new date(system.currenttimemillis())));
newes.add(new news(2, "杜甫", new date(system.currenttimemillis()+8200)));
newes.add(new news(3, "賈寶玉",new date(system.currenttimemillis()-6000)));
return newes;
}
}
第三步:創建控制器servlet
package com.jph.sj.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.jph.sj.model.news;
import com.jph.sj.service.newsservice;
import com.jph.sj.service.impl.newsservicebean;
/**
* 負責響應客戶端的請求:http://xxx/newslistservlet/newslistservlet
*/
public class newslistservlet extends httpservlet {
private static final long serialversionuid = 1l;
private newsservice newsservice = new newsservicebean();
protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
dopost(request, response);
}
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
list<news> newes = newsservice.getlastnews();//獲取最新的視頻資訊
//[{id:20,title:"xxx",timelength:90},{id:10,title:"xbx",timelength:20}]
stringbuilder sbjson = new stringbuilder();
//將list集合封裝成json格式的字符串
sbjson.append('[');
for(news news : newes){
sbjson.append('{');
sbjson.append("id:").append(news.getid()).append(",");
sbjson.append("title:\"").append(news.gettitle()).append("\",");
sbjson.append("publishdate:").append(news.getpublishdate().gettime());
sbjson.append("},");
}
sbjson.deletecharat(sbjson.length() - 1);//刪除字符串末尾的逗號
sbjson.append(']');
request.setattribute("json", sbjson.tostring());
request.getrequestdispatcher("/web-inf/page/jsonnewslist.jsp").forward(request, response);
}
}
第四步:創建jsonnewslist.jsp頁面
<%@ page language="java" contenttype="text/plain; charset=utf-8" pageencoding="utf-8"%>
${json}
至此服務器端項目已經完成。下面開始創建android端項目。
二、創建android端:
android端項目結構:
第一步:創建業務所需的javabean
提示:因為服務器端和android端項目都是用java語言實現的,所以一些組件可以共用,javabean便是其中之一。此時我們在搭建android端項目的時候,完全可以將服務器端項目中javabean拿來用。
第二步:創建android端項目的業務邏輯層
核心代碼:getandparsejson:
package com.jph.gj.service;
import java.io.bytearrayoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.net.httpurlconnection;
import java.net.url;
import java.util.arraylist;
import java.util.date;
import java.util.list;
import org.json.jsonarray;
import org.json.jsonexception;
import org.json.jsonobject;
import com.jph.model.news;
import android.os.handler;
import android.os.message;
/**
* 獲取并解析網絡上的json
* @author jph
* date:2014.09.26
*/
public class getandparsejson {
private string url="http://10.219.61.117:8080/serverforjson/newslistservlet";
public static final int parsesuccwss=0x2001;
private handler handler;
public getandparsejson(handler handler) {
// todo auto-generated constructor stub
this.handler=handler;
}
/**
* 獲取網絡上的xml
*/
public void getjsonfrominternet () {
new thread(new runnable() {
@override
public void run() {
// todo auto-generated method stub
try {
httpurlconnection conn=(httpurlconnection) new url(url).openconnection();
conn.setconnecttimeout(5000);
conn.setrequestmethod("get");
if (conn.getresponsecode()==200) {
inputstream inputstream=conn.getinputstream();
list<news>listnews=parsejson(inputstream);
if (listnews.size()>0) {
message msg=new message();
msg.what=parsesuccwss;//通知ui線程json解析完成
msg.obj=listnews;//將解析出的數據傳遞給ui線程
handler.sendmessage(msg);
}
}
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}).start();
}
/**
* 解析json格式的輸入流轉換成list
* @param inputstream
* @return list
*/
protected list<news> parsejson(inputstream inputstream) {
// todo auto-generated method stub
list<news>listnews=new arraylist<news>();
byte[]jsonbytes=convertistobytearray(inputstream);
string json=new string(jsonbytes);
try {
jsonarray jsonarray=new jsonarray(json);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject jobject=jsonarray.getjsonobject(i);
int id=jobject.getint("id");
string id="code43380">
package com.jph.gj.activity;
import java.text.simpledateformat;
import java.util.arraylist;
import java.util.date;
import java.util.hashmap;
import java.util.list;
import java.util.map;
import com.jph.gj.r;
import com.jph.gj.service.getandparsejson;
import com.jph.model.news;
import android.os.bundle;
import android.os.handler;
import android.os.message;
import android.app.activity;
import android.widget.listview;
import android.widget.simpleadapter;
/**
* 獲取網絡上的json
* @author jph
* date:2014.09.26
*/
public class mainactivity extends activity {
private list<news>listnews;
private listview list;
handler mhandler=new handler(){
@override
public void handlemessage(message msg) {
// todo auto-generated method stub
switch (msg.what) {
case getandparsejson.parsesuccwss:
listnews=(list<news>) msg.obj;
initdata();
break;
}
super.handlemessage(msg);
}
};
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
list=(listview)findviewbyid(r.id.list);
getandparsejson getandparsejson=new getandparsejson(mhandler);
getandparsejson.getjsonfrominternet();
}
/**
* 將解析后的xml填充到listview
*/
protected void initdata() {
// todo auto-generated method stub
list<map<string, object>>items=new arraylist<map<string,object>>();
for (news news:listnews) {
map<string, object>item=new hashmap<string, object>();
item.put("id", news.getid());
item.put("title", news.gettitle());
item.put("time", convertdate(news.getpublishdate()));
items.add(item);
}
simpleadapter adapter=new simpleadapter(this, items, r.layout.line, new string[]
{"id","title","time"}, new int[]{r.id.tvid,r.id.tvtitle,r.id.tvtime});
list.setadapter(adapter);
}
private string convertdate(date publishdate) {
// todo auto-generated method stub
simpledateformat sdf=new simpledateformat("yyyy-mm-dd hh-mm-ss");
return sdf.format(publishdate);
}
}
至此android端項目已經完成了。下面就讓我們看一下app運行效果吧:
android運行效果圖: