Android开发入门之采用JSON格式返回数据给资讯客户端
2013-07-10 21:40
621 查看
上一个应用服务器是采用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;
}
运行:
这次我们采用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;
}
运行:
相关文章推荐
- Android学习笔记---26_采用JSON格式返回数据给资讯客户端,效率上要高于xml文件解析和传输
- Android之从网络中获取数据并返回客户端的两种方式:XML格式返回与Json格式返回
- 服务器采用JSON格式返回数据给安卓客户端
- Android之从网络中获取数据并返回客户端的两种方式:XML格式返回与Json格式返回
- Android之从网络中获取数据并返回客户端的两种方式:XML格式返回与Json格式返回
- Android之从网络中获取数据并返回客户端的两种方式:XML格式返回与Json格式返回
- 服务器采用JSON格式返回数据给安卓客户端
- Android客户端处理服务器端返回的Json格式数据
- 开发android客户端需要了解的知识--JSON数据解析
- Android开发 解析JSON数据格式 如何去掉JSON数据文件的BOM头
- 【android开发】ANDROID处理JSON格式的数据
- Android 客户端通过内置API(HttpClient) 访问 服务器(用Spring MVC 架构) 返回的json数据全过程
- 客户端POST提交、服务器返回json格式数据的demo
- Android访问网络系列之--服务端返回XML或JSON格式数据,Android 进行解析并显示
- Android访问网络系列之--服务端返回XML或JSON格式数据,Android 进行解析并显示
- Android开发入门之采用ListView实现数据列表显示
- Android 客户端通过内置API(HttpClient) 访问 服务器(用Spring MVC 架构) 返回的json数据全过程
- 开发android客户端需要了解的知识--JSON数据解析
- 基于JDK6的JAX-WX为客户端提供XML与JSON格式数据服务,以及客户端采用AXIS调用案例
- 安卓客户端开发:XML和JSON两种数据交换格式的比较