android中获取json数据格式,Android:网络:获取JSON格式数据

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}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值