现在的位置: 首页 > 综合 > 正文

Android开发入门之采用JSON格式返回数据给资讯客户端

2017年04月01日 ⁄ 综合 ⁄ 共 3106字 ⁄ 字号 评论关闭

上一个应用服务器是采用XML格式返回数据给Android客户端的,

这次我们采用JSON格式返回数据给客户端。

ListServlet:

package cn.leigo.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 cn.leigo.domain.News;
import cn.leigo.service.VideoNewsService;
import cn.leigo.service.impl.VideoNewsServiceImpl;

public class ListServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private VideoNewsService service = new VideoNewsServiceImpl();

	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> videos = service.getLastNews();
		String format = request.getParameter("format");
		if ("json".equals(format)) {
			// [{"id":12, "title":"喜洋洋与灰太郎全集", "timelength":60},{"id":35,
			// "title":"实拍船载直升东海救援演习", "timelength":10},{"id":56,
			// "title":"喀麦隆VS荷兰", "timelength":40}]
			StringBuilder json = new StringBuilder();
			json.append("[");
			for (News news : videos) {
				json.append("{");
				json.append("\"id\"").append(":").append(news.getId()).append(",");
				json.append("\"title\"").append(":\"").append(news.getTitle())
						.append("\",");
				json.append("\"timelength\"").append(":")
						.append(news.getTimelength());
				json.append("},");
			}
			json.deleteCharAt(json.length() - 1);
			json.append("]");
			request.setAttribute("json", json.toString());
			request.getRequestDispatcher("/WEB-INF/page/jsonvideonews.jsp")
					.forward(request, response);
		} else {
			request.setAttribute("videos", videos);
			request.getRequestDispatcher("/WEB-INF/page/videonews.jsp")
					.forward(request, response);
		}
	}
}

jsonvideonews.jsp:

<%@ page language="java" contentType="text/plain; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib
	uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
${json}

Android客户端:

VideoNewsService.java:

/**
	 * 获取最新的视频资讯
	 * 
	 * @return
	 * @throws IOException
	 * @throws XmlPullParserException
	 * @throws JSONException
	 */
	public static List<News> getJSONLastNews() throws IOException,
			XmlPullParserException, JSONException {
		String path = "http://192.168.1.100:8080/videonews/ListServlet?format=json";
		List<News> videonews = new ArrayList<News>();
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			InputStream inputStream = conn.getInputStream();
			videonews = parseJSON(inputStream);
		}
		return videonews;
	}

	/**
	 * 解析服务器返回的JSON数据
	 * 
	 * @param inputStream
	 * @return
	 * @throws IOException
	 * @throws JSONException
	 */
	public static List<News> parseJSON(InputStream inputStream)
			throws IOException, JSONException {
		List<News> videonews = new ArrayList<News>();
		News news = null;
		byte[] data = StreamTool.read(inputStream);
		String json = new String(data, "UTF-8");
		JSONArray jsonArray = new JSONArray(json);
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			int id = jsonObject.getInt("id");
			String title = jsonObject.getString("title");
			int timelength = jsonObject.getInt("timelength");
			news = new News(id, title, timelength);
			videonews.add(news);
		}
		return videonews;
	}

运行:

抱歉!评论已关闭.