为要获取网络上的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运行效果图: