码迷,mamicode.com
首页 > 移动开发 > 详细

android与服务器交互总结(json,post,xUtils,Volley)

时间:2016-09-12 14:21:05      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:

http://www.23code.com/tu-biao-chart/

从无到有,从来没有接触过Json,以及与服务器的交互。然后慢慢的熟悉,了解了一点。把我学到的东西简单的做个总结,也做个记录,万一以后用到,就不用到处找了。

 

主要是简单的数据交互,就是字符串的交互,传数据,取数据。刚开始用的普通方法,后来研究了下xUtils框架。

服务器端有人开发,这一块不是我负责,所以我只负责客户端传数据以及接受数据后的处理就OK了。

 

传递数据的形式,主要是看服务端的接口怎么写,服务器是接受JSON字符串,还是要form表单格式(我认为form表单格式就是键值对)。

 

xUtils:

不需要关联library,就下载jar包,复制到libs下就可以了,这是下载地址:http://download.csdn.net/detail/u012975370/9003713

还有就是,你如果想使用library到自己的项目下,注意一点主项目文件和library库文件,必须在同一个文件夹目录下,否则运行项目是报错的

http://blog.csdn.net/dj0379/article/details/38356773

项目原码地址:https://github.com/wyouflf/xUtils

http://www.gbtags.com/gb/share/4360.htm

 

Volley:

初识Volley的基本用法:http://www.apihome.cn/view-detail-70211.html

使用Volley加载网络图片:http://www.apihome.cn/view-detail-70212.html

定制自己的Request:http://www.apihome.cn/view-detail-70213.html

 

还有一些框架:KJFeame和Afinal

KJFrame:

http://git.oschina.net/kymjs/KJFrameForAndroid

http://www.codeceo.com/article/Android-orm-kjframeforandroid.html

 

1.要发送到服务器端的是以JSON字符串的形式发送的。(下面的格式)

 

[java] view plain copy
  1. {"device":"hwG620S-UL00","brand":"HUAWEI","model":"G620S-UL00","imei":"865242025001258","romversion":"G620S-UL00V100R001C17B264"}  

 

 

[java] view plain copy
  1. private void sendData1() {  
  2.         new Thread(new Runnable() {  
  3.             @Override  
  4.             public void run() {  
  5.                 Log.i(TEST_TAG, "2222");  
  6.                 try {  
  7.   
  8.                     HttpPost post = new HttpPost(ACTIVATE_PATH);// post请求  
  9.                     // 先封装一个JSON对象  
  10.                     JSONObject param = new JSONObject();  
  11.                     param.put("romversion", serviceInfoMap.get("romversion"));  
  12.                     param.put("brand", serviceInfoMap.get("brand"));  
  13.                     param.put("model", serviceInfoMap.get("model"));  
  14.                     param.put("device", serviceInfoMap.get("device"));  
  15.                     param.put("imei", serviceInfoMap.get("imei"));  
  16.                     // 绑定到请求Entry  
  17.                     StringEntity se = new StringEntity(param.toString(),  
  18.                             "utf-8");  
  19.                     post.setEntity(se);  
  20.                     Log.i(TEST_TAG, "JSON为---> " + param.toString());  
  21.                     // JSON为--->  
  22.                     // {"device":"hwG620S-UL00","brand":"HUAWEI","model":"G620S-UL00","imei":"8<span style="white-space:pre">                 </span>// 65242025001258","romversion":"G620S-UL00V100R001C17B264"}  
  23.   
  24.                     // 发送请求  
  25.                     HttpParams params = new BasicHttpParams();  
  26.                     DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient(  
  27.                             params);  
  28.                     localDefaultHttpClient.getParams().setParameter(  
  29.                             "http.connection.timeout", Integer.valueOf(30000));  
  30.                     localDefaultHttpClient.getParams().setParameter(  
  31.                             "http.socket.timeout", Integer.valueOf(30000));  
  32.                     HttpResponse response = localDefaultHttpClient  
  33.                             .execute(post);  
  34.                     // 得到应答的字符串,这也是一个JSON格式保存的数据  
  35.                     String retStr = EntityUtils.toString(response.getEntity());  
  36.                     // 生成JSON对象  
  37.                     JSONObject result = new JSONObject(retStr);  
  38.                     int status_value = response.getStatusLine().getStatusCode();  
  39.                     Log.i(TEST_TAG, "" + status_value);  
  40.                     String statusValue = "";  
  41.                     statusValue = result.getString("status");  
  42.                     Log.i(TEST_TAG, statusValue);  
  43.                     if (!statusValue.equals("")) {  
  44.                         // 如果不为空,说明取到了数据,然后就先关闭进去条  
  45.                         mHandler.sendEmptyMessage(CLOSE_DIALOG);  
  46.                         // 然后判断值是否==1,来决定弹出哪个dialog  
  47.                         // 激活成功,就把值传到系统的contentprovider,然后永久保存  
  48.                         if (Integer.parseInt(statusValue) == 1) {  
  49.                             mHandler.sendEmptyMessage(SHOW_SUCCESS);  
  50.                             // 将值设置成1  
  51.                             Settings.System.putInt(getContentResolver(),  
  52.                                     SETTING_MODIFY_NAME, 1);  
  53.                         } else { // 只要是不为1外的其他值,都算失败,弹出失败的dialog  
  54.                             mHandler.sendEmptyMessage(SHOW_FAILURE);  
  55.                         }  
  56.                     }  
  57.   
  58.                 } catch (UnsupportedEncodingException e) {  
  59.                     e.printStackTrace();  
  60.                 } catch (ClientProtocolException e) {  
  61.                     e.printStackTrace();  
  62.                     mHandler.sendEmptyMessage(CONTENT_STATUS);  
  63.                 } catch (SocketException e) {  
  64.                     mHandler.sendEmptyMessage(CONTENT_STATUS);  
  65.                 } catch (IOException e) {  
  66.                     mHandler.sendEmptyMessage(CONTENT_STATUS);  
  67.                     e.printStackTrace();  
  68.                 } catch (JSONException e) {  
  69.                     mHandler.sendEmptyMessage(CONTENT_STATUS);  
  70.                     e.printStackTrace();  
  71.                 }  
  72.             }  
  73.         }).start();  
  74.     }  

 

 

2.以form表单的格式发送到服务端

将传递的数据打印出来,格式是这样的,和json串是不一样的。[romversion=G620S-UL00V100R001C17B264, brand=HUAWEI, model=G620S-UL00, device=hwG620S-UL00, imei=865242024756522]

 

[java] view plain copy
  1. private void sendData1() {  
  2.         new Thread(new Runnable() {  
  3.             @Override  
  4.             public void run() {  
  5.                 Log.i(TEST_TAG, "2222");  
  6.                 try {  
  7.   
  8.                     HttpPost post = new HttpPost(ACTIVATE_PATH);// post请求  
  9.                     // 设置添加对象  
  10.                     List<NameValuePair> paramsForm = new ArrayList<NameValuePair>();  
  11.                     paramsForm.add(new BasicNameValuePair("romversion",  
  12.                             serviceInfoMap.get("romversion")));  
  13.                     paramsForm.add(new BasicNameValuePair("brand",  
  14.                             serviceInfoMap.get("brand")));  
  15.                     paramsForm.add(new BasicNameValuePair("model",  
  16.                             serviceInfoMap.get("model")));  
  17.                     paramsForm.add(new BasicNameValuePair("device",  
  18.                             serviceInfoMap.get("device")));  
  19.                     paramsForm.add(new BasicNameValuePair("imei",  
  20.                             serviceInfoMap.get("imei")));  
  21.                     Log.i(TEST_TAG, paramsForm.toString());  
  22.                     post.setEntity(new UrlEncodedFormEntity(paramsForm,  
  23.                             HTTP.UTF_8));  
  24.   
  25.                     // 发送请求  
  26.                     HttpParams params = new BasicHttpParams();  
  27.                     DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient(  
  28.                             params);  
  29.                     localDefaultHttpClient.getParams().setParameter(  
  30.                             "http.connection.timeout", Integer.valueOf(30000));  
  31.                     localDefaultHttpClient.getParams().setParameter(  
  32.                             "http.socket.timeout", Integer.valueOf(30000));  
  33.                     HttpResponse response = localDefaultHttpClient  
  34.                             .execute(post);  
  35.                     // 得到应答的字符串,这也是一个JSON格式保存的数据  
  36.                     String retStr = EntityUtils.toString(response.getEntity());  
  37.                     // 生成JSON对象  
  38.                     JSONObject result = new JSONObject(retStr);  
  39.                     int status_value = response.getStatusLine().getStatusCode();  
  40.                     Log.i(TEST_TAG, "" + status_value);  
  41.                     String statusValue = "";  
  42.                     statusValue = result.getString("status");  
  43.                     Log.i(TEST_TAG, "status: " + statusValue);  
  44.                     Log.i(TEST_TAG, "datatime: " + result.getString("datatime"));  
  45.                     Log.i(TEST_TAG, "message: " + result.getString("message"));  
  46.                     if (!statusValue.equals("")) {  
  47.                         // 如果不为空,说明取到了数据,然后就先关闭进去条  
  48.                         mHandler.sendEmptyMessage(CLOSE_DIALOG);  
  49.                         // 然后判断值是否==1,来决定弹出哪个dialog  
  50.                         // 激活成功,就把值传到系统的contentprovider,然后永久保存  
  51.                         if (Integer.parseInt(statusValue) == 1) {  
  52.                             // 将值设置成1。需要加权限  
  53.                             Settings.System.putInt(getContentResolver(),  
  54.                                     SETTING_MODIFY_NAME, 1);  
  55.                             mHandler.sendEmptyMessage(SHOW_SUCCESS);  
  56.                         } else { // 只要是不为1外的其他值,都算失败,弹出失败的dialog  
  57.                             mHandler.sendEmptyMessage(SHOW_FAILURE);  
  58.                         }  
  59.                     }  
  60.   
  61.                 } catch (UnsupportedEncodingException e) {  
  62.                     e.printStackTrace();  
  63.                     mHandler.sendEmptyMessage(SHOW_FAILURE);  
  64.                     mHandler.sendEmptyMessage(CONTENT_STATUS);  
  65.                 } catch (ClientProtocolException e) {  
  66.                     e.printStackTrace();  
  67.                     mHandler.sendEmptyMessage(SHOW_FAILURE);  
  68.                     mHandler.sendEmptyMessage(CONTENT_STATUS);  
  69.                 } catch (SocketException e) {  
  70.                     mHandler.sendEmptyMessage(SHOW_FAILURE);  
  71.                     mHandler.sendEmptyMessage(CONTENT_STATUS);  
  72.                 } catch (IOException e) {  
  73.                     mHandler.sendEmptyMessage(SHOW_FAILURE);  
  74.                     mHandler.sendEmptyMessage(CONTENT_STATUS);  
  75.                     e.printStackTrace();  
  76.                 } catch (JSONException e) {  
  77.                     mHandler.sendEmptyMessage(SHOW_FAILURE);  
  78.                     mHandler.sendEmptyMessage(CONTENT_STATUS);  
  79.                     e.printStackTrace();  
  80.                 }  
  81.             }  
  82.         }).start();  
  83.     }  



 

3.xUtils框架的post上传数据,表单格式

 

[java] view plain copy
  1. /** 
  2.      * 表单格式传送(键值对) 
  3.      */  
  4.     private void xUtilsFrame() {  
  5.         RequestParams params = new RequestParams();  
  6.         params.addBodyParameter("romversion", serviceInfoMap.get("romversion"));  
  7.         params.addBodyParameter("brand", serviceInfoMap.get("brand"));  
  8.         params.addBodyParameter("model", serviceInfoMap.get("model"));  
  9.         params.addBodyParameter("device", serviceInfoMap.get("device"));  
  10.         params.addBodyParameter("imei", serviceInfoMap.get("imei"));  
  11.         Log.i(TEST_TAG, params.getEntity().toString());  
  12.   
  13.         HttpUtils http = new HttpUtils();  
  14.         http.configCurrentHttpCacheExpiry(1000 * 10);  
  15.         http.send(HttpMethod.POST, ACTIVATE_PATH, params,  
  16.                 new RequestCallBack<String>() {  
  17.   
  18.                     @Override  
  19.                     public void onSuccess(ResponseInfo<String> responseInfo) {  
  20.                         Log.i(TEST_TAG, "接收到的结果为---》" + responseInfo.result);  
  21.                         Log.i(TEST_TAG, "请求码为--->" + responseInfo.statusCode);  
  22.                         try {  
  23.                             JSONObject jsonObject = new JSONObject(  
  24.                                     responseInfo.result);  
  25.                             Log.i(TEST_TAG, jsonObject.getString("message"));  
  26.                             if (jsonObject.getString("status").equals("1")) {  
  27.                                 mHandler.sendEmptyMessage(CLOSE_DIALOG);  
  28.                                 mHandler.sendEmptyMessage(SHOW_SUCCESS);  
  29.                                 Settings.System.putInt(getContentResolver(),  
  30.                                         SETTING_MODIFY_NAME, 1);  
  31.                             } else {  
  32.                                 mHandler.sendEmptyMessage(CLOSE_DIALOG);  
  33.                                 mHandler.sendEmptyMessage(SHOW_FAILURE);  
  34.                             }  
  35.                         } catch (JSONException e) {  
  36.                             // TODO Auto-generated catch block  
  37.                             e.printStackTrace();  
  38.                         }  
  39.                     }  
  40.   
  41.                     @Override  
  42.                     public void onFailure(HttpException error, String msg) {  
  43.                         Toast.makeText(getApplicationContext(), "失败了",  
  44.                                 Toast.LENGTH_LONG).show();  
  45.                     }  
  46.                 });  
  47.     }  

 

4.xUtils框架,json数据格式

 

[java] view plain copy
  1. /** 
  2.      * 发送json字符串 
  3.      */  
  4.     private void xUtilsFrame2() {  
  5.         try {  
  6.             RequestParams params = new RequestParams();  
  7.             // 先封装一个JSON对象  
  8.             JSONObject param = new JSONObject();  
  9.             param.put("romversion", serviceInfoMap.get("romversion"));  
  10.             param.put("brand", serviceInfoMap.get("brand"));  
  11.             param.put("model", serviceInfoMap.get("model"));  
  12.             param.put("device", serviceInfoMap.get("device"));  
  13.             param.put("imei", serviceInfoMap.get("imei"));  
  14.             StringEntity sEntity = new StringEntity(param.toString(), "utf-8");  
  15.             params.setBodyEntity(sEntity);  
  16.             Log.i(TEST_TAG, "params-->" + params.toString()); // params-->com.lidroid.xutils.http.RequestParams@41c74e10  
  17.             Log.i(TEST_TAG, "param-->" + param.toString()); // param-->{"device":"hwG620S-UL00","brand":"HUAWEI","model":"G620S-UL00","imei":"865242024756522","romversion":"G620S-UL00V100R001C17B264"}  
  18.             Log.i(TEST_TAG, "param-entity-->" + sEntity.toString()); // param-entity-->org.apache.http.entity.StringEntity@41c482f0  
  19.   
  20.             HttpUtils http = new HttpUtils();  
  21.             http.configCurrentHttpCacheExpiry(1000 * 10);  
  22.             http.send(HttpMethod.POST, ACTIVATE_PATH, params,  
  23.                     new RequestCallBack<String>() {  
  24.   
  25.                         @Override  
  26.                         public void onSuccess(ResponseInfo<String> responseInfo) {  
  27.                             Log.i(TEST_TAG, "接收到的结果为---》" + responseInfo.result); // 接收到的结果为---》{"status":"2","datatime":1437444596,"message":"参数无效!"}  
  28.                             Log.i(TEST_TAG, "请求码为--->"  
  29.                                     + responseInfo.statusCode);  
  30.                             try {  
  31.                                 JSONObject jsonObject = new JSONObject(  
  32.                                         responseInfo.result);  
  33.                                 Log.i(TEST_TAG, jsonObject.getString("message"));  
  34.                                 if (jsonObject.getString("status").equals("1")) {  
  35.                                     mHandler.sendEmptyMessage(CLOSE_DIALOG);  
  36.                                     mHandler.sendEmptyMessage(SHOW_SUCCESS);  
  37.                                     Settings.System.putInt(  
  38.                                             getContentResolver(),  
  39.                                             SETTING_MODIFY_NAME, 1);  
  40.                                 } else {  
  41.                                     mHandler.sendEmptyMessage(CLOSE_DIALOG);  
  42.                                     mHandler.sendEmptyMessage(SHOW_FAILURE);  
  43.                                 }  
  44.                             } catch (JSONException e) {  
  45.                                 // TODO Auto-generated catch block  
  46.                                 e.printStackTrace();  
  47.                             }  
  48.                         }  
  49.   
  50.                         @Override  
  51.                         public void onFailure(HttpException error, String msg) {  
  52.                             Toast.makeText(getApplicationContext(), "失败了",  
  53.                                     Toast.LENGTH_LONG).show();  
  54.                         }  
  55.                     });  
  56.   
  57.         } catch (JSONException e1) {  
  58.             // TODO Auto-generated catch block  
  59.             e1.printStackTrace();  
  60.         } catch (UnsupportedEncodingException e) {  
  61.             // TODO Auto-generated catch block  
  62.             e.printStackTrace();  
  63.         }  
  64.     }  

 

5.Volley框架:StringRequest,from表单

 

[java] view plain copy
  1. /** 
  2.      * Volley框架:StirngRequest(需要导入Volley.jar包到libs目录下,需要加internet权限) 
  3.      */  
  4.     private void volleyFrameSR() {  
  5.         // 第一步:创建一个RequestQueue对象  
  6.         final RequestQueue mQueue = Volley.newRequestQueue(this);  
  7.         // 第二步:创建一个StringRequest对象  
  8.         StringRequest stringRequest = new StringRequest(Method.POST,  
  9.                 ACTIVATE_PATH, new Response.Listener<String>() {  
  10.                     // 服务器响应成功的回调  
  11.                     @Override  
  12.                     public void onResponse(String response) {  
  13.                         Log.i(TEST_TAG, "返回结果为--->" + response);  
  14.                         try {  
  15.                             JSONObject jsonObject = new JSONObject(response);  
  16.                             Log.i(TEST_TAG,  
  17.                                     "status-->"  
  18.                                             + jsonObject.getString("status"));  
  19.                             Log.i(TEST_TAG,  
  20.                                     "message-->"  
  21.                                             + jsonObject.getString("message"));  
  22.                             mQueue.cancelAll("StringRequest");  
  23.                             mHandler.sendEmptyMessage(SHOW_SUCCESS);  
  24.                             mHandler.sendEmptyMessage(CLOSE_DIALOG);  
  25.                         } catch (JSONException e) {  
  26.                             // TODO Auto-generated catch block  
  27.                             e.printStackTrace();  
  28.                         }  
  29.                     }  
  30.   
  31.                 }, new Response.ErrorListener() {  
  32.                     // 服务器响应失败的回调  
  33.                     @Override  
  34.                     public void onErrorResponse(VolleyError error) {  
  35.                         Log.e(TEST_TAG, error.getMessage(), error);  
  36.                         mHandler.sendEmptyMessage(SHOW_FAILURE);  
  37.                     }  
  38.                 }) {  
  39.   
  40.             @Override  
  41.             protected Map<String, String> getParams() throws AuthFailureError {  
  42.                 Map<String, String> map = new HashMap<String, String>();  
  43.                 map.put("romversion", serviceInfoMap.get("romversion"));  
  44.                 map.put("brand", serviceInfoMap.get("brand"));  
  45.                 map.put("model", serviceInfoMap.get("model"));  
  46.                 map.put("device", serviceInfoMap.get("device"));  
  47.                 map.put("imei", serviceInfoMap.get("imei"));  
  48.                 Log.i(TEST_TAG, "发送结果为--->" + map.toString());  
  49.                 // 发送结果为--->{device=hwG620S-UL00, brand=HUAWEI,  
  50.                 // model=G620S-UL00, imei=865242024756522,  
  51.                 // romversion=G620S-UL00V100R001C17B264}  
  52.   
  53.                 return map;  
  54.             }  
  55.         };  
  56.         stringRequest.setTag("StringRequest");  
  57.         // 第三步:将StringRequest对象添加到RequestQueue里面  
  58.         mQueue.add(stringRequest);  
  59.     }  

这个写了太多的代码,这是方法的原型:

 

 

[java] view plain copy
  1. StringRequest stringRequest = new StringRequest(Method.POST, url,  listener, errorListener) {    
  2.     @Override    
  3.     protected Map<String, String> getParams() throws AuthFailureError {    
  4.         Map<String, String> map = new HashMap<String, String>();    
  5.         map.put("params1", "value1");    
  6.         map.put("params2", "value2");    
  7.         return map;    
  8.     }    
  9. };    

根据我服务器的接受模式,我觉得他发送的结果是form表单格式

 

6.Volley框架: JsonObjectRequest。 

因为它的方法中传递的的请求参数为JsonObject,目前还没有找到传递form格式的方法。

 

[java] view plain copy
  1. /** 
  2.      * Volley框架:JsonObjectRequest 
  3.      */  
  4.     private void volleyFrameJR() {  
  5.         // 第一步:创建一个RequestQueue对象  
  6.         final RequestQueue mQueue = Volley.newRequestQueue(this);  
  7.   
  8.         JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(  
  9.                 Method.POST, ACTIVATE_PATH, null,  
  10.                 new Response.Listener<JSONObject>() {  
  11.   
  12.                     @Override  
  13.                     public void onResponse(JSONObject response) {  
  14.                         Log.i(TEST_TAG, "返回结果为--->" + response.toString());  
  15.                         try {  
  16.                             // JSONObject jsonObject = new JSONObject(response);  
  17.                             Log.i(TEST_TAG,  
  18.                                     "status-->" + response.getString("status"));  
  19.                             Log.i(TEST_TAG,  
  20.                                     "message-->"  
  21.                                             + response.getString("message"));  
  22.                             mHandler.sendEmptyMessage(SHOW_SUCCESS);  
  23.                             mHandler.sendEmptyMessage(CLOSE_DIALOG);  
  24.                         } catch (JSONException e) {  
  25.                             // TODO Auto-generated catch block  
  26.                             e.printStackTrace();  
  27.                         }  
  28.                     }  
  29.                 }, new Response.ErrorListener() {  
  30.   
  31.                     @Override  
  32.                     public void onErrorResponse(VolleyError error) {  
  33.                         Log.e(TEST_TAG, error.getMessage(), error);  
  34.                         mHandler.sendEmptyMessage(SHOW_FAILURE);  
  35.                     }  
  36.                 }) {  
  37.               
  38.             @Override  
  39.             protected Map<String, String> getPostParams()  
  40.                     throws AuthFailureError {  
  41.                 Map<String, String> map = new HashMap<String, String>();  
  42.                 map.put("romversion", serviceInfoMap.get("romversion"));  
  43.                 map.put("brand", serviceInfoMap.get("brand"));  
  44.                 map.put("model", serviceInfoMap.get("model"));  
  45.                 map.put("device", serviceInfoMap.get("device"));  
  46.                 map.put("imei", serviceInfoMap.get("imei"));  
  47.                 Log.i(TEST_TAG, "发送结果为--->" + map.toString());  
  48.                 return map;  
  49.             }  
  50.   
  51.         };  
  52.         mQueue.add(jsonObjectRequest); // 没有这句就无法交互  
  53.   
  54.     }  

这种方式应该可以,好像getParams也可以,因为服务器写的不是接受json格式数据,所以我没法测试。

 

还有就是去掉重写的方法,不管是getPostParams还是getParams,然后将里面的map集合内容写道,new JsonObjectRequest之前,然后在JsonObject  jsonObject = newJsonObject(map),然后将jsonObject作为第三个参数,这样就传递了一个json字符串到服务器。

 

 

 

7.JsonObject和JsonArray

 

 

[java] view plain copy
  1. //JsonObject和JsonArray区别就是JsonObject是对象形式,JsonArray是数组形式  
  2.         //创建JsonObject第一种方法  
  3.         JSONObject jsonObject = new JSONObject();  
  4.         jsonObject.put("UserName", "ZHULI");  
  5.         jsonObject.put("age", "30");  
  6.         jsonObject.put("workIn", "ALI");  
  7.         System.out.println("jsonObject1:" + jsonObject);  
  8.           
  9.         //创建JsonObject第二种方法  
  10.         HashMap<String, String> hashMap = new HashMap<String, String>();  
  11.         hashMap.put("UserName", "ZHULI");  
  12.         hashMap.put("age", "30");  
  13.         hashMap.put("workIn", "ALI");  
  14.         System.out.println("jsonObject2:" + JSONObject.fromObject(hashMap));  
  15.           
  16.         //创建一个JsonArray方法1  
  17.         JSONArray jsonArray = new JSONArray();  
  18.         jsonArray.add(0, "ZHULI");  
  19.         jsonArray.add(1, "30");  
  20.         jsonArray.add(2, "ALI");  
  21.         System.out.println("jsonArray1:" + jsonArray);  
  22.           
  23.         //创建JsonArray方法2  
  24.         ArrayList<String> arrayList = new ArrayList<String>();  
  25.         arrayList.add("ZHULI");  
  26.         arrayList.add("30");  
  27.         arrayList.add("ALI");  
  28.         System.out.println("jsonArray2:" + JSONArray.fromObject(arrayList));  
  29.           
  30.         //如果JSONArray解析一个HashMap,则会将整个对象的放进一个数组的值中  
  31.         System.out.println("jsonArray FROM HASHMAP:" + JSONArray.fromObject(hashMap));  
  32.           
  33.         //组装一个复杂的JSONArray  
  34.         JSONObject jsonObject2 = new JSONObject();  
  35.         jsonObject2.put("UserName", "ZHULI");  
  36.         jsonObject2.put("age", "30");  
  37.         jsonObject2.put("workIn", "ALI");  
  38.         jsonObject2.element("Array", arrayList);  
  39.         System.out.println("jsonObject2:" + jsonObject2);  


system结果:

 

 

[html] view plain copy
  1. jsonObject1:{"UserName":"ZHULI","age":"30","workIn":"ALI"}  
  2. jsonObject2:{"workIn":"ALI","age":"30","UserName":"ZHULI"}  
  3. jsonArray1:["ZHULI","30","ALI"]  
  4. jsonArray2:["ZHULI","30","ALI"]  
  5. jsonArray FROM HASHMAP:[{"workIn":"ALI","age":"30","UserName":"ZHULI"}]  
  6. jsonObject2:{"UserName":"ZHULI","age":"30","workIn":"ALI","Array":["ZHULI","30","ALI"]}  
[html] view plain copy
  1. </pre><pre name="code" class="html" style="font-size: 13px; margin-top: 0px; margin-bottom: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; line-height: 19.5px; background-color: rgb(254, 254, 242);">  
[html] view plain copy
  1. <span style="font-size:24px;">android读取json数据(遍历JSONObject和JSONArray)</span>  
[html] view plain copy
  1. <pre name="code" class="java">public String getJson(){    
  2.         String jsonString = "{\"FLAG\":\"flag\",\"MESSAGE\":\"SUCCESS\",\"name\":[{\"name\":\"jack\"},{\"name\":\"lucy\"}]}";//json字符串    
  3.         try {    
  4.             JSONObject result = new JSONObject(jsonstring);//转换为JSONObject    
  5.             int num = result.length();    
  6.             JSONArray nameList = result.getJSONArray("name");//获取JSONArray    
  7.             int length = nameList.length();    
  8.             String aa = "";    
  9.             for(int i = 0; i length; i++){//遍历JSONArray    
  10.                 Log.d("debugTest",Integer.toString(i));    
  11.                 JSONObject oj = nameList.getJSONObject(i);    
  12.                 aa = aa + oj.getString("name")+"|";    
  13.                     
  14.             }    
  15.             Iterator<?it = result.keys();    
  16.             String aa2 = "";    
  17.             String bb2 = null;    
  18.             while(it.hasNext()){//遍历JSONObject    
  19.                 bb2 = (String) it.next().toString();    
  20.                 aa2 = aa2 + result.getString(bb2);    
  21.                     
  22.             }    
  23.             return aa;    
  24.         } catch (JSONException e) {    
  25.             throw new RuntimeException(e);    
  26.         }    
  27.     }    



8.生成数组json串

我想要生成的json串为:
{
"languages": [//应用市场所支持的语种信息
  {
"name":"汉语",
"code":"hy",
"selected":"true"
  },
  {
"name":"蒙古语",
"code":"mn"
"selected":"false"
  }
],
"applist_versioncode":"0",
"applist_num":"2",
代码如下:
[java] view plain copy
  1. private void createJsonData() {  
  2.         try {  
  3.             // 存放总的json数据的容器  
  4.             JSONObject jsonObject = new JSONObject();  
  5.   
  6.             /* 
  7.              * 首先,总的josn的第一条的key是languages,他的value是一个数组,数组有两个元素,所以, 
  8.              * languages对应的value是一个JsonArray对象 
  9.              */  
  10.             // 此时生成一个jsonarray来存放language的值的数组  
  11.             JSONArray jsonArrayLang = new JSONArray();  
  12.             // 首先将language的第一条数据,生成jsonObject对象  
  13.             JSONObject joLang0 = new JSONObject();  
  14.             joLang0.put("name", "汉语");  
  15.             joLang0.put("code", "hy");  
  16.             joLang0.put("selected", "true");  
  17.             // 此时,将数组的第一组数据添加到jsonarray中  
  18.             jsonArrayLang.put(0, joLang0);  
  19.   
  20.             // 首先将language的第二条数据,生成jsonObject对象  
  21.             JSONObject joLang1 = new JSONObject();  
  22.             joLang1.put("name", "蒙古语");  
  23.             joLang1.put("code", "mn");  
  24.             joLang1.put("selected", "false");  
  25.             // 此时,将数组的第一组数据添加到jsonarray中  
  26.             jsonArrayLang.put(1, joLang1);  
  27.   
  28.             // 此时,langauge的值已经生成,就是jsonarraylang这个数组格式的数据  
  29.             // 然后,将其添加到总的jsonobject中  
  30.             jsonObject.put("languages", jsonArrayLang);  
  31.             // 添加总jsonobject容器的第二条数据,"applist_versioncode":"0",  
  32.             jsonObject.put("applist_versioncode", "0");  
  33.             // 添加总jsonobject容器的第三条数据,"applist_num":"2",  
  34.             jsonObject.put("applist_num", "2");  
  35.   
  36.             System.out.println(jsonObject.toString());  
  37.   
  38.         } catch (JSONException e) {  
  39.             // TODO Auto-generated catch block  
  40.             e.printStackTrace();  
  41.         }  
  42.     }  
最后输出结果为技术分享

 

 

9.修改json串(带数组)

 

[java] view plain copy
  1. String stt = "{\"languages\":[{\"name\":\"汉语\",\"code\":\"hy\"},"  
  2.             + "{\"name\":\"蒙古语\",\"code\":\"mn\"}]}";  
[java] view plain copy
  1. <span style="white-space:pre">                </span>try {  
  2.                     JSONObject jsonObject = new JSONObject(stt);  
  3.                     System.out.println("修改之前---->" + jsonObject.toString());  
  4.                     JSONArray jsonArray = jsonObject.getJSONArray("languages");  
  5.                     System.out.println("修改之前---->" + jsonArray.toString());  
  6.                     System.out.println("jsonArray.length()---->"  
  7.                             + jsonArray.length());  
  8.                     for (int i = 0; i < jsonArray.length(); i++) {  
  9.                         JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);  
  10.                         System.out.println("jsonObject2---->" + i + "-----"  
  11.                                 + jsonArray.toString());  
  12.                         if (i == (jsonArray.length() - 1)) {  
  13.                             System.out.println("修改之前---->");  
  14.                             jsonObject2.put("name", "法国与");  
  15.                             jsonArray.put(i, jsonObject2);  
  16.                         }  
  17.                     }  
  18.                     jsonArray.put(jsonArray.length(),  
  19.                             (JSONObject) jsonArray.opt(jsonArray.length() - 1));  
  20.                     jsonObject.put("languages", jsonArray);  
  21.                     System.out.println("修改之后---->" + jsonObject.toString());  
  22.                 } catch (JSONException e) {  
  23.                     e.printStackTrace();  
  24.                 }  

修改json串,就需要一层一层读出来,然后key值存在的时候,直接put新值,就会直接替换掉,然后在一层一层添加回去。这样就可以了

android与服务器交互总结(json,post,xUtils,Volley)

标签:

原文地址:http://www.cnblogs.com/wanghuaijun/p/5864520.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!