public class News {
private Integer id;
private String title;
private Integer timelength;
...
}
ListView listView = (ListView) this.findViewById(R.id.listView); try {
List videos =
VideoNewsService.getJSONLastNews();//需修改成你本机的Http请求路径
List> data = new ArrayList>();
for(News news : videos){
HashMap item = new HashMap();
item.put("id", news.getId());
item.put("title", news.getTitle());
item.put("timelength", getResources().getString(R.string.timelength)
+ news.getTimelength()+ getResources().getString(R.string.min));
data.add(item);
}
SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,
new String[]{"title", "timelength"}, new int[]{R.id.title, R.id.timelength});
listView.setAdapter(adapter);
public static List getJSONLastNews() throws Exception{
String path = "http://192.168.0.168:8080/web/ListServlet";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
InputStream inStream = conn.getInputStream();
return parseJSON(inStream);
}
return null;
}
/**
* 解析JSON数据
* @param inStream
* @return
*/
private static List parseJSON(InputStream inStream) throws Exception{
List newses = new ArrayList();
byte[] data = StreamTool.read(inStream);
String json = new String(data);
JSONArray array = new JSONArray(json);
for(int i = 0 ; i < array.length() ; i++){
JSONObject jsonObject = array.getJSONObject(i);
News news = new News(jsonObject.getInt("id"), jsonObject.getString("title"), jsonObject.getInt("timelength"));
newses.add(news);
}
return newses;
}
Servlet:
List videos = service.getLastNews();
// [{id:56,title:"xxxxx",timelength:90},{id:16,title:"xbbx",timelength:20}]
StringBuilder builder = new StringBuilder();
builder.append('[');
for(News news : videos){
builder.append('{');
builder.append("id:").append(news.getId()).append(',');
builder.append("title:\"").append(news.getTitle()).append("\",");
builder.append("timelength:").append(news.getTimelength());
builder.append("},");
}
builder.deleteCharAt(builder.length() - 1);
builder.append(']');
request.setAttribute("json", builder.toString());
request.getRequestDispatcher("/WEB-INF/page/jsonvideonews.jsp").forward(request, response);
JSP:
${json}