一、什么是json

json(Javascript Object Notation)是一种轻量级的数据交换格式,相比于xml这种数据交换格式来说,因为解析xml比较的复杂,而且需要编写大段的代码,所以客户端和服务器的数据交换格式往往通过json来进行交换。尤其是对于web开发来说,json数据格式在客户端直接可以通过javascript来进行解析。

json一共有两种数据结构,一种是以 (key/value)对形式存在的无序的jsonObject对象,一个对象以“{”(左花括号)开始,“}”(右花括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间使用“,”(逗号)分隔。

例如:{"name": "xiaoluo"}, 这就是一个最简单的json对象,对于这种数据格式,key值必须要是string类型,而对于value,则可以是string、number、object、array等数据类型

另一种数据格式就是有序的value的集合,这种形式被称为是jsonArray,数组是值(value)的有序集合。一个数组以“[”(左中括号)开始,“]”(右中括号)结束。值之间使用“,”(逗号)分隔。

 

二.下面介绍一个例子(该例子也是借鉴网友的:附近地址:http://www.cnblogs.com/xiaoluo501395377/p/3446605.html)

1. 首先上结果图

  

     简单的布局显示,第二幅图是要根据服务器的数据返回后显示出来的.

图一:   图二:     

图一是服务端的文件,图二是客户端的文件

2. 首先看服务器上的代码

 

 1 package com.bing.test;
 2 import java.io.IOException;
 3 import java.io.PrintWriter;
 4 import java.util.ArrayList;
 5 import java.util.HashMap;
 6 import java.util.List;
 7 import java.util.Map;
 8 
 9 import javax.servlet.ServletException;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 
14 import com.alibaba.fastjson.JSON;
15 
16 
17 public class CityServlet extends HttpServlet{
18 
19     /**
20      */
21     private static final long serialVersionUID = 1L;
22 
23     public CityServlet(){
24         super();
25     }
26     
27     protected void doGet(HttpServletRequest request,
28             HttpServletResponse response) throws ServletException, IOException
29     {
30         this.doPost(request, response);
31     }
32 
33     protected void doPost(HttpServletRequest request,
34             HttpServletResponse response) throws ServletException, IOException
35     {
36         
37         response.setContentType("text/html;charset=utf-8");
38         request.setCharacterEncoding("utf-8");
39         response.setCharacterEncoding("utf-8");
40         
41         PrintWriter writer = response.getWriter();
42         
43         String type = request.getParameter("type");
44         if("json".equals(type)){
45             List<String> city = new ArrayList<String>();
46             city.add("上海");
47             city.add("北京");
48             city.add("重庆");
49             city.add("四川");
50             city.add("黑龙江");
51             
52             Map<String, List<String>> map = new HashMap<String, List<String>>();
53             map.put("cities", city);
54             
55             String cityString = JSON.toJSONString(map);
56             writer.println(cityString);
57             
58 //            response.sendRedirect("index3.jsp");
59             
60         }
61         writer.flush();
62         writer.close();
63         
64     }
65     
66     
67     
68 }
View Code

如果客户端请求的参数是type=json,则响应给客户端一个json数据格式

不过其中String cityString = JSON.toJSONString(map); JSON类需要用到图一中的一个jar包(WEB-INF/lib/下的fastjson-1.2.4.jar),是ali推出的.用着不错.

下面来看一下关于客户端的代码

(1).首先是样式布局

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     tools:context="com.example.jsontest.MainActivity" >
 6 
 7     <Spinner 
 8         android:id="@+id/city_show"
 9         android:layout_width="wrap_content"
10         android:layout_height="wrap_content"
11         android:layout_alignParentTop="true"
12         android:layout_marginTop="50dp"
13         android:layout_centerInParent="true"/>
14     
15     <Button 
16         android:id="@+id/showBtn"
17         android:layout_width="wrap_content"
18         android:layout_height="wrap_content"
19         android:layout_alignParentBottom="true"
20         android:layout_marginBottom="50dp"
21         android:layout_centerInParent="true"
22         android:text="@string/show"/>
23     
24 
25 </RelativeLayout>
View Code

布局文件so easy,没有什么好说的

(2). 然后是MainActivity

  1 package com.example.jsontest;
  2 
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 
  6 import android.app.Activity;
  7 import android.app.Dialog;
  8 import android.app.ProgressDialog;
  9 import android.os.Bundle;
 10 import android.os.Handler;
 11 import android.os.Message;
 12 import android.view.View;
 13 import android.widget.ArrayAdapter;
 14 import android.widget.Button;
 15 import android.widget.SimpleAdapter;
 16 import android.widget.Spinner;
 17 
 18 
 19 public class MainActivity extends Activity {
 20 
 21     public static final int LOADING_DOWN = 0x0001;
 22     
 23     private List<String> city = new ArrayList<String>();
 24     
 25     private final String CITY_PATH_JSON = "http://10.1.8.142:8080/JSONTest/city?type=json";
 26     
 27     private Spinner spinner;
 28     private Button showBtn;
 29     
 30     private ProgressDialog dialog;
 31     
 32     public Handler handler = new Handler(){
 33         @Override
 34         public void handleMessage(Message msg) {
 35             
 36             switch (msg.what) {
 37             case LOADING_DOWN:
 38                 city = (List<String>) msg.obj;
 39                 showContent();
 40                 break;
 41             default:
 42                 break;
 43             }
 44         }
 45     };
 46     
 47     
 48     
 49     @Override
 50     protected void onCreate(Bundle savedInstanceState) {
 51         super.onCreate(savedInstanceState);
 52         setContentView(R.layout.activity_main);
 53         
 54         initView();
 55         
 56     }
 57     
 58     private void initView(){
 59         
 60         showBtn = (Button) findViewById(R.id.showBtn);
 61         spinner = (Spinner) findViewById(R.id.city_show);
 62         
 63         dialog = new ProgressDialog(this);
 64     }
 65     
 66     
 67     @Override
 68     protected void onStart() {
 69         super.onStart();
 70         
 71         if(city.size() == 0){
 72             city.add("城市");
 73         }else{
 74             
 75         }
 76         
 77         spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, city));
 78         spinner.setSelection(0);
 79         
 80         showBtn.setOnClickListener(new Button.OnClickListener() {
 81             @Override
 82             public void onClick(View view) {
 83                 showCity();
 84             }
 85         });
 86         
 87     }
 88     
 89     private void showCity(){
 90         
 91         new MyAsyncTask(MainActivity.this, dialog).execute(CITY_PATH_JSON);
 92         
 93     }
 94     
 95    
 96     private void showContent(){
 97         
 98         spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, city));
 99         spinner.setSelection(0);
100     }
101     
102 
103 }
View Code

private final String CITY_PATH_JSON = "http://10.1.8.142:8080/JSONTest/city?type=json";  IP地址换成自己本机上tomcat运行时的IP

然后是几个其它工具类等等 

1. MyAsyncTast.java类 异步线程处理

 1 package com.example.jsontest;
 2 
 3 import java.io.IOException;
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 
 7 import android.R.integer;
 8 import android.app.ProgressDialog;
 9 import android.content.Context;
10 import android.os.AsyncTask;
11 import android.os.Message;
12 import android.util.Log;
13 
14 import com.bing.tool.HttpUtils2;
15 import com.bing.tool.JsonUtils;
16 
17 public class MyAsyncTask extends AsyncTask<String, integer, List<String>> {
18 
19     private static final String TAG = "MyAsyncTask";
20     
21     public static final int LOADING_DOWN = 0x0001;
22     
23     private List<String> result = new ArrayList<String>();
24     
25     private MainActivity activity;
26     
27     private ProgressDialog dialog;
28     
29     public MyAsyncTask(Object obj){
30         
31         if(obj instanceof ProgressDialog){
32             this.dialog = (ProgressDialog)obj;
33         }
34     }
35     
36     public MyAsyncTask(MainActivity activity, Object obj){
37         
38         if(obj instanceof ProgressDialog){
39             this.dialog = (ProgressDialog)obj;
40         }
41         
42         if(activity instanceof MainActivity){
43             this.activity = activity;
44         }
45     }
46     
47     
48     @Override
49     protected void onPreExecute() {
50         
51         showDialog();
52     }
53     
54     private void showDialog(){
55         dialog.show();
56         dialog.setTitle("提示信息");
57         dialog.setMessage("loading......");
58         dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
59         dialog.setCancelable(false);
60     }
61     
62     @Override
63     protected List<String> doInBackground(String... arg0) {
64         
65         try {
66             Log.i(TAG, "back content: " + arg0[0]);
67             String content = HttpUtils2.sendPostMessage(arg0[0], "UTF-8");
68             
69             Log.i(TAG, "back content: " + content);
70             result = JsonUtils.parseJsonContent(content);
71                     
72         } catch (IOException e) {
73             e.printStackTrace();
74         }
75         
76         return result;
77     }
78 
79     
80     @Override
81     protected void onPostExecute(List<String> result) {
82         
83         Message msg = new Message();
84         msg.what = LOADING_DOWN;
85         msg.obj = result;
86         activity.handler.sendMessage(msg);
87         dialog.dismiss();
88         
89     }
90     
91     
92 }
View Code

2. JsonUtils.java 类,用于处理JSONObject

 1 package com.bing.tool;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.json.JSONArray;
 7 import org.json.JSONException;
 8 import org.json.JSONObject;
 9 
10 public class JsonUtils {
11     
12     
13     /**
14      * @param content
15      * @return
16      */
17     public static List<String> parseJsonContent(String content){
18         
19         List<String> contents = new ArrayList<String>();
20         
21         JSONObject jsonObj;
22         try {
23             jsonObj = new JSONObject(content);
24             
25             JSONArray jsonArray = jsonObj.getJSONArray("cities");
26             
27             for(int i = 0; i < jsonArray.length(); i++){
28                 
29                 contents.add(jsonArray.getString(i));
30             }
31             
32         }catch (JSONException e) {
33             e.printStackTrace();
34         }
35         
36         return contents;
37         
38     }
39     
40 
41 }
View Code

3. HttpUtils2.java类,用于请求报务器获取所得的数据

 1 package com.bing.tool;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStreamReader;
 5 
 6 import org.apache.http.HttpEntity;
 7 import org.apache.http.HttpResponse;
 8 import org.apache.http.HttpStatus;
 9 import org.apache.http.client.ClientProtocolException;
10 import org.apache.http.client.HttpClient;
11 import org.apache.http.client.methods.HttpGet;
12 import org.apache.http.impl.client.DefaultHttpClient;
13 import org.apache.http.util.EntityUtils;
14 
15 import android.util.Log;
16 
17 public class HttpUtils2 {
18 
19 public static String sendPostMessage(String url, String encode) throws IOException{
20         
21         String result = null;
22         HttpGet request = new HttpGet(url);
23         HttpClient httpClient = new DefaultHttpClient();
24         
25         try {
26             HttpResponse response = httpClient.execute(request);
27             if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
28                 Log.i("here", "here");
29                 HttpEntity httpEntity = response.getEntity();
30                 if(httpEntity != null){
31                     result = EntityUtils.toString(httpEntity);
32                     Log.i("result", "result: " + result);
33                 }
34             }
35             
36         }catch (Exception e) {
37             e.printStackTrace();
38         }finally{
39             httpClient.getConnectionManager().shutdown();
40         }
41         
42         return result;
43         
44     }
45     
46     
47 }
View Code

4. AndoridMainfest.xml

 当然别往了开启我们的网络授权

  <uses-permission android:name="android.permission.INTERNET"/>

5. 运行程序

 跑程序,就可以完成了客户端与服务器端通过json来进行数据的交换

 

在这过程中遇到一些问题:

1. at org.apache.catalina.loader.WebappClassLoader.loadClass. 就是关于导包的问题

 过程中不知什么原因,不过将包放在WEB-INF/lib/下,然后build bath就可以了.

 

新手学android,大部分内容都是照搬的,不过其中过程中还是费了一点时间,如果觉得该文章太浅蒲,勿喷,谢谢

 

posted on 2015-06-19 17:14  tiandibing  阅读(557)  评论(0编辑  收藏  举报