服务器采用JSON格式返回数据给安卓客户端

最近打算做一个酒店无线点餐的APP,需要将图片放在服务器端的文件夹下,客户端通过更新菜单按钮可以获得最新的菜品信息。要获取图片的信息首先需要得到图片的名称、对应的菜品价格以及图片所在的路径,因此需要在服务器端搜索文件夹下的所有图片并将数据打包成JSON格式转发给客户端,具体格式为[{name="菜名",price=价格,path="文件路径",category="菜品分类:如川菜、湘菜等"}]。服务器端采用servlet+jsp部署在Tomcat中,下面给出获取文件目录下所有图片信息并封装成JSON格式的代码。服务器端图片存储的目录如下所示。


<span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;">import java.io.File;
public class JsonUtils {
	/**
	* 通过遍历文件目录获取图片资源信息
	* 文件格式为:菜名$价格.jpg
	*/
	public static String getJson(String strPath) {
		StringBuilder builder = new StringBuilder();
		builder.append('[');
		File file = new File(strPath);
		File[] fileList = file.listFiles();
		for (int i = 0; i < fileList.length; i++) {
			if (fileList[i].isDirectory()) {
				File mFile = new File(fileList[i].getPath());
				File[] mFileList = mFile.listFiles();
				for (int j = 0; j < mFileList.length; j++) {
					String name = "";
					String price = "";
					String path = "";
					String category = "";
					String str = mFileList[j].getName();
                                        //分割价格和菜名					
                                        String[] strList = str.split("\\$");
					name = strList[0];
					strList = strList[1].split("\\.");
					price = strList[0];
					path = mFileList[j].getPath();
					strList=path.split("\\\\");
					path="";
					for(String mstr:strList){
						path=path+mstr+"\\\\";
					}
					path=path.substring(0, path.length()-2);
					category = mFileList[j].getParent().substring(
							mFileList[j].getParent().lastIndexOf("\\") + 1);
					builder.append("{name:\"").append(name).append("\",");
					builder.append("price:").append(price).append(',');
					builder.append("path:\"").append(path).append("\",");
					builder.append("category:\"").append(category)
							.append("\"},");
				}
			}
		}
		builder.deleteCharAt(builder.length() - 1);
		builder.append(']');
		return builder.toString();

	}
}</span></span></span>
创建一个Servlet文件在goGet()方法中调用getJson()方法,并将客户端请求转向到一个JSP页面,在JSP中通过EL表达式获取Json对象。

<span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;">import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.restaurant.utils.*;

/**
 * Servlet implementation class UpdatePictureServlet
 */
@WebServlet("/UpdatePictureServlet")
public class UpdatePictureServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static String strPath = "E:\\webTest\\Restaurant\\WebContent\\Pictures";

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setAttribute("json", JsonUtils.getJson(strPath));
		request.getRequestDispatcher("/WEB-INF/page/jsondata.jsp").forward(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}</span></span></span>
JSP页面内容如下:

<span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;"><%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${json}</span></span></span>


将项目部署到服务器上,在浏览器中输入:http://localhost:8080/Restaurant/UpdatePictureServlet回车之后的效果如下:



安卓客户端通过HTTP协议获取JSON数据,首先封装一个PictureBean对象,该对象用于接收解析出来的JSON格式,同时创建和该对象对应的数据库表,直接将对象列表存储在SQLite数据库中,方便本地读取。

<span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;">package com.example.domain;

public class PictureBean {
	private int id;
	private String name;
	private int price;
	private String path;
	private String category;

	public PictureBean(String name, int price, String path, String category) {
		this.name = name;
		this.price = price;
		this.path = path;
		this.category = category;
	}

	public PictureBean() {
	}

	@Override
	public String toString() {
		name = getName();
		path = getPath();
		return "PictureBean [name=" + name + ", price=" + price + ", category="
				+ category + "]";
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

	public String getPath() {

		return path;
	}

	public void setPath(String path) {

		this.path = path;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}
}
</span></span></span>


下面是从服务器获取JSON数据并存储在PictureBean对象中的程序代码:

<span style="font-size:18px;"><span style="font-size:18px;">package com.example.service;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.example.domain.PictureBean;
import com.example.utils.StreamTool;

public class UptadePictureService {
	public static List<PictureBean> getJSONPictures() throws Exception {
		String path = "http://192.168.1.103:8080/Restaurant/UpdatePictureServlet";
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		conn.setReadTimeout(5000);
		if (conn.getResponseCode() == 200) {
			InputStream inStream = conn.getInputStream();
			return parseJSON(inStream);
		}
		return null;
	}

	/**
	 * 解析JSON数据
	 * 
	 * @param inStream
	 * @return
	 */
	private static List<PictureBean> parseJSON(InputStream inStream)
			throws Exception {
		List<PictureBean> Pictures = new ArrayList<PictureBean>();
		byte[] data = StreamTool.read(inStream);
		String json = new String(data);
		Log.d("MainActivity", json);
		JSONArray array = new JSONArray(json);
		for (int i = 0; i < array.length(); i++) {
			JSONObject jsonObject = array.getJSONObject(i);
			PictureBean picture = new PictureBean(jsonObject.getString("name"),
					jsonObject.getInt("price"), jsonObject.getString("path"),
					jsonObject.getString("category"));
			Pictures.add(picture);
		}
		return Pictures;
	}

}
</span></span>

以上就是就是把图片数据信息打包成JSON格式,以及安卓客户端获取图片信息并保存为PictureBean对象的全部过程,有关数据库方面的代码比较简单,这里不再贴出来。关于图片的下载以及界面显示部分的内容将在下一篇博客中进行介绍。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值