您好,登錄后才能下訂單哦!
做Android開(kāi)發(fā)的程序員必須知道android客戶(hù)端應(yīng)該如何與服務(wù)端進(jìn)行交互,這里主要介紹的是使用json數(shù)據(jù)進(jìn)行交互。服務(wù)端從數(shù)據(jù)庫(kù)查出數(shù)據(jù)并以json字符串的格式或者map集合的格式返回到客戶(hù)端,客戶(hù)端進(jìn)行解析并輸出到手機(jī)屏幕上。
此處介紹兩種方式:使用Google原生的Gson解析json數(shù)據(jù),使用JSONObject解析json數(shù)據(jù)
一、使用Google原生的Gson解析json數(shù)據(jù):
記得在客戶(hù)端添加gson.jar。
核心代碼:
服務(wù)端:
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 * 對(duì)用戶(hù)操作的控制器類(lèi) * */ @Controller @RequestMapping("tblUserCtrl") public class TblUserCtrl { @Resource(name="tblUserDao") TblUserDao tblUserDao; //添加用戶(hù) @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; } //查看所有用戶(hù) @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; } //刪除用戶(hù) @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; } //修改用戶(hù) @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; } }
客戶(hù)端:
拼接URL的類(lèi):
package com.mfc.urlutils; import java.util.Map; /** * 2017年7月6日06:42:10 * 一些URL需要使用的公用數(shù)據(jù)及方法 * */ 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的參數(shù)部分 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; } }
訪問(wèn)服務(wù)器的類(lèi):
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 * 將客戶(hù)端數(shù)據(jù)傳送到服務(wù)器,并接受服務(wù)器返回的數(shù)據(jù) * */ 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數(shù)據(jù)的類(lèi):
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數(shù)據(jù)的類(lèi) * */ public class GetJsonToEntity { //解析單個(gè)數(shù)據(jù) 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解析工具類(lèi),提供泛型參數(shù) * */ class GsonUtil{ //將json數(shù)據(jù)解析成相應(yīng)的映射對(duì)象 public static <T> T parseJsonWithGson(String jsonData,Class<T> type){ Gson gson=new Gson(); T result = gson.fromJson(jsonData, type); return result; } //將json數(shù)組解析成相應(yīng)的映射對(duì)象列表 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; } }
調(diào)用這些方法的Activity以及實(shí)體類(lèi)省略。
二、使用JSONObject解析json數(shù)據(jù)
注意:服務(wù)端要添加json的jar包。
客戶(hù)端解析json數(shù)據(jù)的代碼:
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的工具類(lèi) * 這里面所有方法的key,都是json一層數(shù)據(jù)的鍵,注意傳數(shù)據(jù)時(shí)調(diào)用本類(lèi)方法的時(shí)候給的key值 * */ public class ParseJson { //解析單條數(shù)據(jù) 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數(shù)組 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數(shù)組數(shù)據(jù) * @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; } /** * 獲取對(duì)象的Map集合數(shù)據(jù) * @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; } }
客戶(hù)端接收服務(wù)端的數(shù)據(jù)方法:
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"; /** * 從服務(wù)器獲取json數(shù)據(jù) * */ 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; } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。