做Android开发的程序员必须知道android客户端应该如何与服务端进行交互,这里主要介绍的是使用json数据进行交互。服务端从数据库查出数据并以json字符串的格式或者map集合的格式返回到客户端,客户端进行解析并输出到手机屏幕上。
此处介绍两种方式:使用Google原生的Gson解析json数据,使用JSONObject解析json数据
一、使用Google原生的Gson解析json数据:
记得在客户端添加gson.jar。
核心代码:
服务端:
package com.mfc.ctrl; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.mfc.dao.TblUserDao; import com.mfc.entity.TblUser; /** * 2017年7月6日06:26:40 * 对用户操作的控制器类 * */ @Controller @RequestMapping("tblUserCtrl") public class TblUserCtrl { @Resource(name="tblUserDao") TblUserDao tblUserDao; //添加用户 @RequestMapping("addUser") @ResponseBody public Object addUser(HttpServletRequest request){ String uname=request.getParameter("uname"); String upass=request.getParameter("upass"); float money=Float.parseFloat(request.getParameter("money")); System.out.println(uname+"==="+upass+"==="+money); TblUser tblUser=new TblUser(); tblUser.setMoney(money); tblUser.setUname(uname); tblUser.setUpass(upass); tblUserDao.addUser(tblUser); Map<String, Object> map=new HashMap<String, Object>(); map.put("success", "success"); return map; } //查看所有用户 @RequestMapping("getAllUser") @ResponseBody public Object getAllUser(){ List<TblUser> list = tblUserDao.selectAllUser(); Map<String, Object> map=new HashMap<String, Object>(); map.put("list", list); return map; } //删除用户 @RequestMapping("delUser") @ResponseBody public Object delUser(HttpServletRequest request){ int uid=Integer.parseInt(request.getParameter("uid")); TblUser tblUser=tblUserDao.getUserById(uid); tblUserDao.delUser(tblUser); Map<String, Object> map=new HashMap<String, Object>(); map.put("success", "success"); return map; } //修改用户 @RequestMapping("updateUser") @ResponseBody public Object updateUser(HttpServletRequest request){ int uid=Integer.parseInt(request.getParameter("uid")); String uname=request.getParameter("uname"); String upass=request.getParameter("upass"); float money=Float.parseFloat(request.getParameter("money")); TblUser tblUser=new TblUser(); tblUser.setMoney(money); tblUser.setUid(uid); tblUser.setUname(uname); tblUser.setUpass(upass); tblUserDao.updateUser(tblUser); Map<String, Object> map=new HashMap<String, Object>(); map.put("success", "success"); return map; } }
客户端:
拼接URL的类:
package com.mfc.urlutils; import java.util.Map; /** * 2017年7月6日06:42:10 * 一些URL需要使用的公用数据及方法 * */ public class SomePublicData { //公用path public static final String path="http://192.168.0.111:8080/MyeclipseService/tblUserCtrl/"; //拼接path public static String fullPath(String pathlast, Map<String, String> map) { StringBuilder builder = new StringBuilder(); String realPath = null; if(map!=null && !map.isEmpty()){ //拼接url的参数部分 for (Map.Entry<String, String> entrty : map.entrySet()) { builder.append(entrty.getKey()).append("="); builder.append(entrty.getValue()).append("&"); } builder.deleteCharAt(builder.length()-1); //拼接最后完整的url realPath = SomePublicData.path+pathlast+"?"+builder; return realPath; } return SomePublicData.path+pathlast; } }
访问服务器的类:
package com.mfc.urlutils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; /** * 2017年7月6日06:55:26 * 将客户端数据传送到服务器,并接受服务器返回的数据 * */ public class SendDateToServer { public static String sendToServer(String path){ StringBuilder builder=new StringBuilder(); try { HttpClient client=new DefaultHttpClient(); if(path != null && path.length() > 0){ if(client != null){ HttpParams httpParams=client.getParams(); if(httpParams != null){ HttpConnectionParams.setConnectionTimeout(httpParams, 60000); HttpConnectionParams.setSoTimeout(httpParams, 60000); HttpGet get=new HttpGet(path); if(get != null){ HttpResponse httpResponse=client.execute(get); if(httpResponse != null){ HttpEntity entity=httpResponse.getEntity(); if(entity != null){ BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent())); String line = null; while((line = bufferedReader.readLine()) != null){ builder.append(String.format("%s\n", line)); } bufferedReader.close(); } } } } } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } }
解析json数据的类:
package com.mfc.jsonutils; import java.util.ArrayList; import java.util.List; import org.json.JSONObject; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.mfc.entity.TblUser; /** * 2017年7月6日07:15:32 * 解析json数据的类 * */ public class GetJsonToEntity { //解析单个数据 public static TblUser getTblUser(String jsonString){ Gson gson = new Gson(); TblUser tblUser = gson.fromJson(jsonString, TblUser.class); return tblUser; } //解析list集合 public static List<TblUser> getTblUserList(String gsonString) { List<TblUser> listusers=GsonUtil.parseJsonArrayWithGson(gsonString, TblUser.class); return listusers; } } /** * 2017年7月6日15:45:43 * 封装的json解析工具类,提供泛型参数 * */ class GsonUtil{ //将json数据解析成相应的映射对象 public static <T> T parseJsonWithGson(String jsonData,Class<T> type){ Gson gson=new Gson(); T result = gson.fromJson(jsonData, type); return result; } //将json数组解析成相应的映射对象列表 public static <T> List<T> parseJsonArrayWithGson(String jsonData,Class<T> type){ List<T> result = new ArrayList<T>(); try { Gson gson = new Gson(); JSONObject jsonObject=new JSONObject(jsonData); String string=jsonObject.getString("list"); JsonArray arry = new JsonParser().parse(string).getAsJsonArray(); for (JsonElement jsonElement : arry) { result.add(gson.fromJson(jsonElement, type)); } } catch (Exception e) { e.printStackTrace(); } return result; } }
调用这些方法的Activity以及实体类省略。
二、使用JSONObject解析json数据
注意:服务端要添加json的jar包。
客户端解析json数据的代码:
package com.mfc.jsonutils; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.mfc.entity.Task; /** * 2017年6月25日21:34:44 * 解析json的工具类 * 这里面所有方法的key,都是json一层数据的键,注意传数据时调用本类方法的时候给的key值 * */ public class ParseJson { //解析单条数据 public static Task getTask(String key,String json){ Task task=new Task(); try { JSONObject jsonObject=new JSONObject(json); JSONObject taskObject=jsonObject.getJSONObject(key); task.setTid(taskObject.getInt("uid")); task.setContent(taskObject.getString("content")); task.setIssuccess(taskObject.getInt("issuccess")); task.setTasktime(taskObject.getString("tasktime")); task.setTitle(taskObject.getString("title")); task.setUid(taskObject.getInt("uid")); } catch (JSONException e) { e.printStackTrace(); } return task; } //解析list集合 public static List<Task> getListTask(String key,String jsonString){ List<Task> list=new ArrayList<Task>(); try { JSONObject jsonObject=new JSONObject(jsonString); //解析json数组 JSONArray array=jsonObject.getJSONArray(key); for (int i = 0; i < array.length(); i++) { JSONObject jsonObject2=array.getJSONObject(i); Task task=new Task(); task.setTid(jsonObject2.getInt("uid")); task.setContent(jsonObject2.getString("content")); task.setIssuccess(jsonObject2.getInt("issuccess")); task.setTasktime(jsonObject2.getString("tasktime")); task.setTitle(jsonObject2.getString("title")); task.setUid(jsonObject2.getInt("uid")); list.add(task); } } catch (JSONException e) { e.printStackTrace(); } return list; } /** * 获取String数组数据 * @param key * @param jsonString * @return */ public static List<String> getList(String key,String jsonString){ List<String> list = new ArrayList<String>(); try { JSONObject jsonObject = new JSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray(key); for(int i=0;i<jsonArray.length();i++){ String msg = jsonArray.getString(i); list.add(msg); } } catch (JSONException e) { e.printStackTrace(); } return list; } /** * 获取对象的Map集合数据 * @param key * @param jsonString * @return */ public static List<Map<String,Object>> getListMap(String key,String jsonString){ List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); try { JSONObject jsonObject = new JSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray(key); for(int i=0;i<jsonArray.length();i++){ JSONObject jsonObject2 = jsonArray.getJSONObject(i); Map<String,Object> map = new HashMap<String, Object>(); Iterator<String> iterator = jsonObject2.keys(); while(iterator.hasNext()){ String json_key = iterator.next(); Object json_value = jsonObject2.get(json_key); if(json_value==null){ json_value = ""; } map.put(json_key, json_value); } list.add(map); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; } }
客户端接收服务端的数据方法:
package com.mfc.urlutils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.apache.http.entity.StringEntity; import android.util.Log; public class HttpUtils { static String TAG="HttpUtils"; /** * 从服务器获取json数据 * */ public static String getJsonContent(String path){ String jsonString=""; try { URL url=new URL(path); HttpURLConnection connection=(HttpURLConnection) url.openConnection(); connection.setConnectTimeout(3000); connection.setRequestMethod("GET"); connection.setDoInput(true); int code=connection.getResponseCode(); if(code==200){ InputStream inputStream=connection.getInputStream(); ByteArrayOutputStream outputStream=new ByteArrayOutputStream(); int len=0; byte[] data=new byte[1024]; while ((len=inputStream.read(data))!=-1) { outputStream.write(data, 0, len); } jsonString=new String(outputStream.toByteArray()); Log.i(TAG, jsonString); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return jsonString; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。