修改软件服务器json返回数据格式,服务器采用JSON格式返回数据给安卓客户端

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

2ecc3a808e6924e490c236d1e847f907.png

packagecom.restaurant.utils;importjava.io.File;public classJsonUtils {public staticString getJson(String strPath) { StringBuilder builder= newStringBuilder(); builder.append('['); File file= newFile(strPath); File[] fileList=file.listFiles();for (int i = 0; i < fileList.length; i++) {if(fileList[i].isDirectory()) { File mFile= newFile(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(']');returnbuilder.toString(); } }

创建一个Servlet文件在其doGet()方法中调用上面的getJson()方法,并将客户端请求转到一个JSP页面,在JSP中通过EL表达式获取出JSON字符串。

packagecom.restaurant.servlet;importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;import com.restaurant.utils.*;/*** Servlet implementation class UpdatePictureServlet*/@WebServlet("/UpdatePictureServlet")public class UpdatePictureServlet extendsHttpServlet {private static final long serialVersionUID = 1L;private static String strPath = "E:\\webTest\\Restaurant\\WebContent\\Pictures";/***@seeHttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response)*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {//TODO Auto-generated method stub

request.setAttribute("json", JsonUtils.getJson(strPath)); request.getRequestDispatcher("/WEB-INF/page/jsondata.jsp").forward(request, response); }/***@seeHttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)*/

protected voiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {//TODO Auto-generated method stub

} }

JSP页面内容如下:

${json}

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

6121082174ac8fae2e0b6499ac2fe0a7.png

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

packagecom.example.service;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.URL;importjava.util.ArrayList;importjava.util.List;importorg.json.JSONArray;importorg.json.JSONObject;importandroid.util.Log;importcom.example.domain.PictureBean;importcom.example.utils.StreamTool;public classUptadePictureService {public static List getJSONPictures() throwsException { String path= "http://192.168.1.103:8080/Restaurant/UpdatePictureServlet"; URL url= newURL(path); HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET");if (conn.getResponseCode() == 200) { InputStream inStream=conn.getInputStream();returnparseJSON(inStream); }return null; }/*** 解析JSON数据 * *@paraminStream *@return

*/

private static ListparseJSON(InputStream inStream)throwsException { List Pictures = new ArrayList();byte[] data =StreamTool.read(inStream); String json= newString(data); Log.d("MainActivity", json); JSONArray array= newJSONArray(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); }returnPictures; } }

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值