首先我们创建服务端
-
News.java
public class News {
private int id;
private String title;
private Date publishDate;
public int getId() {
return id;
}
public void setId(int 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;
}
public News(int id, String title, Date publishDate) {
super();
this.id = id;
this.title = title;
this.publishDate = publishDate;
}
public News() {
super();
}
@Override
public String toString() {
return "News [id=" + id + ", publishDate=" + publishDate + ", title="
+ title + "]";
}
}
-
JsonDaoImpl .java
public class JsonDaoImpl implements JsonDao {
public List<News> getAllNews() {
List<News> newList=new ArrayList<News>();
News n1=new News(1,"李白",new Date(System.currentTimeMillis()));
News n2=new News(2,"杜甫",new Date(System.currentTimeMillis()));
News n3=new News(3,"白居易",new Date(System.currentTimeMillis()));
//将对象添加到集合里去
newList.add(n1);
newList.add(n2);
newList.add(n3);
return newList;
}
}
-
JsonServlet.java (Servlet)
public class JsonServlet extends HttpServlet {
private JsonDaoImpl jsonDaoImpl = new JsonDaoImpl();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 拿到集合
List<News> newses = jsonDaoImpl.getAllNews();
StringBuilder sbJson = new StringBuilder();
sbJson.append('[');
// 按照json数据格式进行重组
for (News news : newses) {
sbJson.append('{');
sbJson.append("id:").append(news.getId()).append(",");
sbJson.append("title:\"").append(news.getTitle()).append("\",");
sbJson.append("publishDate:").append(news.getPublishDate());
sbJson.append("},");
}
sbJson.deleteCharAt(sbJson.length() - 1);
sbJson.append(']');
request.setAttribute("newses", sbJson);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
}
-
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
${newses}
-
测试:
接下来我们创建客户端(客户端的需求就是:通过HttpURLConnection来访问服务端得到Json文件并经过Json解析器来进行解析转变成集合显示到listview里面进行展示)
-
News.java
import java.util.Date;
public class News {
private int id;
private String title;
private Date time;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public News(int id, String title, Date time) {
super();
this.id = id;
this.title = title;
this.time = time;
}
public News() {
super();
}
}
-
GetAndParseJson.java (用来解析json)
public class GetAndParseJson {
//你要訪問的地址
private String url="http://100.77.31.240:8080/JsonService/JsonServlet";
public static final int PARSESUCCWSS=0x2016;
private Handler handler;
public GetAndParseJson(Handler handler) {
this.handler=handler;
}
/**
* 获取网络上的json
*/
public void getJsonFromInternet () {
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpURLConnection conn=(HttpURLConnection) new URL(url).openConnection();
conn.setConnectTimeout(3000);
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) {
e.printStackTrace();
}
}
}).start();
}
/**
* 解析json格式的输入流转换成List
*/
protected List<News> parseJson(InputStream inputStream)throws Exception {
List<News>listNews=new ArrayList<News>();
byte[]jsonBytes=convertIsToByteArray(inputStream);
String json=new String(jsonBytes);
try {
JSONArray jsonArray=new JSONArray(json);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObject=jsonArray.getJSONObject(i);
int id=jObject.getInt("id");
String title=jObject.getString("title");
Date time = sdf.parse(jObject.getString("publishDate"));
News news=new News(id, title, time);
listNews.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
}
return listNews;
}
/**
* 将输入流转化成ByteArray
*/
private byte[] convertIsToByteArray(InputStream inputStream) {
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte buffer[]=new byte[1024];
int length=0;
try {
while ((length=inputStream.read(buffer))!=-1) {
baos.write(buffer, 0, length);
}
inputStream.close();
baos.flush();
} catch (IOException e) {
e.printStackTrace();
}
return baos.toByteArray();
}
}
-
MainActivity.java (主布局)
public class MainActivity extends Activity {
private List<News>listNews;
private ListView list;
//用來接收GetAndParseJson.PARSESUCCWSS
Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
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.lv);
GetAndParseJson getAndParseJson=new GetAndParseJson(mHandler);
getAndParseJson.getJsonFromInternet();//執行它返回一個listNews集合
}
/**
* 将解析后的json填充到ListView
*/
protected void initData() {
List<Map<String, Object>> jsonlist=new ArrayList<Map<String,Object>>();
for (News news:listNews) {
Map<String, Object> map=new HashMap<String, Object>();
map.put("id", news.getId());
map.put("title", news.getTitle());
map.put("time", news.getTime());
jsonlist.add(map);
}
SimpleAdapter adapter=new SimpleAdapter(this, jsonlist, R.layout.text, new String[]
{"id","title","time"}, new int[]{R.id.id,R.id.title,R.id.time});
list.setAdapter(adapter);
}
}
-
注:联网权限不要忘记加!!!
<uses-permission android:name="android.permission.INTERNET"/>
-
演示: