Android JSON、GSON、FastJson的封装与解析

声明:
1、本帖只提供代码,不深入讲解原理。如果读者想要深入了解,那就不要在这个帖子上浪费时间了
2、客户端用的是Google官方的Volley访问服务器,具体了解Volley请戳 这里
3、本帖三种数据解析的DEMO都用到了下面这个Person类,贴出来:

 1 public class Person {
 2     private String name;
 3     private int age;
 4     private String address;
 5 
 6     public Person() {
 7 
 8     }
 9 
10     public Person(String name, int age, String address) {
11         super();
12         this.name = name;
13         this.age = age;
14         this.address = address;
15     }
16 
17     public String getName() {
18         return name;
19     }
20 
21     public void setName(String name) {
22         this.name = name;
23     }
24 
25     public int getAge() {
26         return age;
27     }
28 
29     public void setAge(int age) {
30         this.age = age;
31     }
32 
33     public String getAddress() {
34         return address;
35     }
36 
37     public void setAddress(String address) {
38         this.address = address;
39     }
40 }
Person实体类

 

一、JSON的封装和解析

服务端 的代码如下:

在MyEclipse中新建一个Web Project,把JSON操作所需要的JAR包(点击这里下载)导入到项目中。

1 public class JsonTools {
2     // 封装JSON字符串
3     public static String createJsonString(String key, Object value) {
4         JSONObject jsonObject = new JSONObject();
5         jsonObject.put(key, value);
6         return jsonObject.toString();
7     }
8 }
封装JSON字符串的工具类
 1 public class JsonService {
 2     public Person getPerson() {
 3         return new Person("张三", 20, "北京");
 4     }
 5 
 6     public List<Person> getPersons() {
 7         List<Person> list = new ArrayList<Person>();
 8         list.add(new Person("张三", 20, "北京"));
 9         list.add(new Person("李四", 22, "上海"));
10         list.add(new Person("王五", 21, "天津"));
11         return list;
12     }
13 
14     public List<String> getStrings() {
15         List<String> list = new ArrayList<String>();
16         list.add("星期一");
17         list.add("星期二");
18         list.add("星期三");
19         list.add("星期四");
20         list.add("星期五");
21         return list;
22     }
23 
24     public List<Map<String, String>> getMaps() {
25         List<Map<String, String>> list = new ArrayList<Map<String, String>>();
26         Map<String, String> hashMap = new HashMap<String, String>();
27         hashMap.put("name", "Jack");
28         hashMap.put("phone", "123456789");
29         hashMap.put("address", "Canada");
30         list.add(hashMap);
31         hashMap = new HashMap<String, String>();
32         hashMap.put("name", "Rose");
33         hashMap.put("phone", "123789456");
34         hashMap.put("address", "America");
35         list.add(hashMap);
36         hashMap = new HashMap<String, String>();
37         hashMap.put("name", "Tom");
38         hashMap.put("phone", "789456123");
39         hashMap.put("address", "China");
40         list.add(hashMap);
41         return list;
42     }
43 }
生成几种简单类型的数据的类
 1 public class JsonServlet extends HttpServlet {
 2     private JsonService service;
 3 
 4     public JsonServlet() {
 5         super();
 6     }
 7 
 8     public void destroy() {
 9         super.destroy();
10     }
11 
12     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
13         response.setContentType("text/html;charset=UTF-8");
14         request.setCharacterEncoding("UTF-8");
15         response.setCharacterEncoding("UTF-8");
16         PrintWriter out = response.getWriter();
17 
18         String key = request.getParameter("key");
19         if (key.equals("person")) {
20             Person person = service.getPerson();
21             out.println(JsonTools.createJsonString("person", person));
22         } else if (key.equals("persons")) {
23             List<Person> persons = service.getPersons();
24             out.println(JsonTools.createJsonString("persons", persons));
25         } else if (key.equals("strings")) {
26             List<String> strings = service.getStrings();
27             out.println(JsonTools.createJsonString("strings", strings));
28         } else if (key.equals("maps")) {
29             List<Map<String, String>> maps = service.getMaps();
30             out.println(JsonTools.createJsonString("maps", maps));
31         }
32     }
33 
34     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
35         doGet(request, response);
36     }
37 
38     public void init() throws ServletException {
39         service = new JsonService();
40     }
41 }
测试用的Servlet类

对于输入的URL不同,结果如下:

客户端 的代码如下:

在解析JSON时,客户端不需要导入任何包。

 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     android:background="#ffffffff" >
 6 
 7     <TextView
 8         android:id="@+id/person_result"
 9         android:layout_width="wrap_content"
10         android:layout_height="wrap_content"
11         android:textColor="#ff000000"
12         android:textSize="15.0sp" />
13 
14     <TextView
15         android:id="@+id/persons_result"
16         android:layout_width="wrap_content"
17         android:layout_height="wrap_content"
18         android:layout_below="@id/person_result"
19         android:layout_marginTop="10.0dip"
20         android:textColor="#ff000000"
21         android:textSize="15.0sp" />
22 
23     <TextView
24         android:id="@+id/strings_result"
25         android:layout_width="wrap_content"
26         android:layout_height="wrap_content"
27         android:layout_below="@id/persons_result"
28         android:layout_marginTop="10.0dip"
29         android:textColor="#ff000000"
30         android:textSize="15.0sp" />
31 
32     <TextView
33         android:id="@+id/maps_result"
34         android:layout_width="wrap_content"
35         android:layout_height="wrap_content"
36         android:layout_below="@id/strings_result"
37         android:layout_marginTop="10.0dip"
38         android:textColor="#ff000000"
39         android:textSize="15.0sp" />
40 
41 </RelativeLayout>
MainActivity类的布局代码
 1 public class JsonTools {
 2     public void getResult(TextView view, JSONObject jsonObject) {
 3         switch (view.getId()) {
 4         case R.id.person_result:
 5             view.setText(getPerson(jsonObject));
 6             break;
 7         case R.id.persons_result:
 8             view.setText(getPersons(jsonObject));
 9             break;
10         case R.id.strings_result:
11             view.setText(getStrings(jsonObject));
12             break;
13         case R.id.maps_result:
14             view.setText(getMaps(jsonObject));
15             break;
16         }
17     }
18 
19     private String getPerson(JSONObject jsonObject) {
20         String result = "-->从服务器获取Person数据\n";
21         try {
22             JSONObject personObject = jsonObject.getJSONObject("person");
23             result += "姓名:" + personObject.getString("name") + "\n";
24             result += "年龄:" + personObject.getString("age") + "\n";
25             result += "地址:" + personObject.getString("address");
26         } catch (JSONException e) {
27             e.printStackTrace();
28         }
29         return result;
30     }
31 
32     private String getPersons(JSONObject jsonObject) {
33         String result = "-->从服务器获取List<Person>数据\n";
34         try {
35             JSONArray jsonArray = jsonObject.getJSONArray("persons");
36             for (int i = 0; i < jsonArray.length(); i++) {
37                 result += "-第" + (i + 1) + "组数据:\n";
38                 JSONObject subObject = jsonArray.getJSONObject(i);
39                 result += "姓名:" + subObject.getString("name") + "\n";
40                 result += "年龄:" + subObject.getString("age") + "\n";
41                 result += "地址:" + subObject.getString("address");
42                 if (i != jsonArray.length() - 1) {
43                     result += "\n";
44                 }
45             }
46         } catch (JSONException e) {
47             e.printStackTrace();
48         }
49         return result;
50     }
51 
52     private String getStrings(JSONObject jsonObject) {
53         String result = "-->从服务器获取List<String>数据\n";
54         try {
55             JSONArray jsonArray = jsonObject.getJSONArray("strings");
56             for (int i = 0; i < jsonArray.length(); i++) {
57                 result += jsonArray.getString(i);
58                 if (i != jsonArray.length() - 1) {
59                     result += " -> ";
60                 }
61             }
62         } catch (JSONException e) {
63             e.printStackTrace();
64         }
65         return result;
66     }
67 
68     private String getMaps(JSONObject jsonObject) {
69         String result = "-->从服务器获取List<HashMap<String,String>>数据\n";
70         try {
71             JSONArray jsonArray = jsonObject.getJSONArray("maps");
72             for (int i = 0; i < jsonArray.length(); i++) {
73                 result += "-第" + (i + 1) + "组数据:\n";
74                 JSONObject subObject = jsonArray.getJSONObject(i);
75                 result += "姓名:" + subObject.getString("name") + "\n";
76                 result += "电话:" + subObject.getString("phone") + "\n";
77                 result += "地址:" + subObject.getString("address");
78                 if (i != jsonArray.length() - 1) {
79                     result += "\n";
80                 }
81             }
82         } catch (JSONException e) {
83             e.printStackTrace();
84         }
85         return result;
86     }
87 }
处理JSON的工具类
 1 public class MainActivity extends Activity {
 2     private final String url = "http://192.168.1.102:8080/JsonServer/JsonServlet";
 3     private TextView person_result, persons_result, strings_result, maps_result;
 4     private JsonTools jsonTools;
 5 
 6     @Override
 7     protected void onCreate(Bundle savedInstanceState) {
 8         super.onCreate(savedInstanceState);
 9         setContentView(R.layout.activity_main);
10         person_result = (TextView) findViewById(R.id.person_result);
11         persons_result = (TextView) findViewById(R.id.persons_result);
12         strings_result = (TextView) findViewById(R.id.strings_result);
13         maps_result = (TextView) findViewById(R.id.maps_result);
14         jsonTools = new JsonTools();
15 
16         getResponseToView(url + "?key=person", "json_person", person_result);
17         getResponseToView(url + "?key=persons", "json_persons", persons_result);
18         getResponseToView(url + "?key=strings", "json_strings", strings_result);
19         getResponseToView(url + "?key=maps", "json_maps", maps_result);
20     }
21 
22     private void getResponseToView(String url, String tag, final TextView view) {
23         StringRequest request = new StringRequest(Method.GET, url, new Listener<String>() {
24             @Override
25             public void onResponse(String response) {
26                 try {
27                     JSONObject resultObject = new JSONObject(response);
28                     jsonTools.getResult(view, resultObject);
29                 } catch (JSONException e) {
30                     e.printStackTrace();
31                 }
32             }
33         }, new Response.ErrorListener() {
34             @Override
35             public void onErrorResponse(VolleyError arg0) {
36                 view.setText(arg0.toString());
37             }
38         });
39         request.setTag(tag);
40         MyApplication.getRequestQueue().add(request);
41     }
42 
43     @Override
44     protected void onStop() {
45         super.onStop();
46         MyApplication.getRequestQueue().cancelAll("JsonRequest");
47     }
48 }
主界面MainActivity的代码

运行结果如下图所示:

 

二、GSON的封装和解析

服务端 的代码如下(生成数据的类GsonService和JsonService类相同,这里就不再贴了):

在MyEclipse中新建一个Web Project,将GSON操作所需要的JAR包(点击这里下载)导入到项目中。

1 public class GsonTools {
2     // 生成GSON字符串
3     public static String createGsonString(Object value) {
4         Gson gson = new Gson();
5         String gsonString = gson.toJson(value);
6         return gsonString;
7     }
8 }
生成GSON字符串的类
 1 public class GsonServlet extends HttpServlet {
 2     private GsonService service;
 3 
 4     public GsonServlet() {
 5         super();
 6     }
 7 
 8     public void destroy() {
 9         super.destroy();
10     }
11 
12     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
13         response.setContentType("text/html;charset=UTF-8");
14         request.setCharacterEncoding("UTF-8");
15         response.setCharacterEncoding("UTF-8");
16         PrintWriter out = response.getWriter();
17 
18         String key = request.getParameter("key");
19         if (key.equals("person")) {
20             Person person = service.getPerson();
21             out.println(GsonTools.createGsonString(person));
22         } else if (key.equals("persons")) {
23             List<Person> persons = service.getPersons();
24             out.println(GsonTools.createGsonString(persons));
25         } else if (key.equals("strings")) {
26             List<String> strings = service.getStrings();
27             out.println(GsonTools.createGsonString(strings));
28         } else if (key.equals("maps")) {
29             List<Map<String, String>> maps = service.getMaps();
30             out.println(GsonTools.createGsonString(maps));
31         }
32     }
33 
34     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
35         doGet(request, response);
36     }
37 
38     public void init() throws ServletException {
39         service = new GsonService();
40     }
41 }
测试用的Servlet类

对于输入的URL不同,结果如下:

客户端 的代码如下(MainActivity类的布局代码和上面的一样):

在解析GSON时,客户端需要导入和服务端相同的包。

 1 public class GsonTools {
 2     public static <T> T getPerson(String jsonString, Class<T> cls) {
 3         T t = null;
 4         try {
 5             Gson gson = new Gson();
 6             t = gson.fromJson(jsonString, cls);
 7         } catch (Exception e) {
 8             e.printStackTrace();
 9         }
10         return t;
11     }
12 
13     public static <T> List<T> getPersons(String jsonString, Class<T[]> cls) {
14         List<T> list = null;
15         try {
16             Gson gson = new Gson();
17             list = Arrays.asList(gson.fromJson(jsonString, cls));
18         } catch (Exception e) {
19             e.printStackTrace();
20         }
21         return list;
22     }
23 
24     public static List<String> getStrings(String jsonString) {
25         List<String> list = null;
26         try {
27             Gson gson = new Gson();
28             list = gson.fromJson(jsonString, new TypeToken<List<String>>() {
29             }.getType());
30         } catch (Exception e) {
31             e.printStackTrace();
32         }
33         return list;
34     }
35 
36     public static <T> List<HashMap<String, T>> getMaps(String jsonString,Class<T> cls) {
37         List<HashMap<String, T>> list = new ArrayList<HashMap<String, T>>();
38         try {
39             Gson gson = new Gson();
40             list = gson.fromJson(jsonString, new TypeToken<List<HashMap<String, T>>>() {
41             }.getType());
42         } catch (Exception e) {
43             e.printStackTrace();
44         }
45         return list;
46     }
47 }
处理受到的数据的工具类
 1 public class MainActivity extends Activity {
 2     private final String url = "http://192.168.1.102:8080/GsonServer/GsonServlet";
 3     private TextView person_result, persons_result, strings_result, maps_result;
 4 
 5     @Override
 6     protected void onCreate(Bundle savedInstanceState) {
 7         super.onCreate(savedInstanceState);
 8         setContentView(R.layout.activity_main);
 9         person_result = (TextView) findViewById(R.id.person_result);
10         persons_result = (TextView) findViewById(R.id.persons_result);
11         strings_result = (TextView) findViewById(R.id.strings_result);
12         maps_result = (TextView) findViewById(R.id.maps_result);
13 
14         getResultToView(url + "?key=person", "GsonPerson", person_result);
15         getResultToView(url + "?key=persons", "GsonPersons", persons_result);
16         getResultToView(url + "?key=strings", "GsonStrings", strings_result);
17         getResultToView(url + "?key=maps", "GsonMaps", maps_result);
18     }
19 
20     private void getResultToView(String url, String tag, final TextView view) {
21         StringRequest request = new StringRequest(Method.GET, url, new Listener<String>() {
22             @Override
23             public void onResponse(String response) {
24                 manageResponse(response, view);
25             }
26         }, new ErrorListener() {
27             @Override
28             public void onErrorResponse(VolleyError arg0) {
29                 view.setText(arg0.toString());
30             }
31         });
32         request.setTag(tag);
33         MyApplication.getRequestQueue().add(request);
34     }
35 
36     // 将GsonTools类返回的处理好的JAVA对象进行排版并输出到对应TextView中
37     private void manageResponse(String response, TextView view) {
38         switch (view.getId()) {
39         case R.id.person_result:
40             addTextToView(view, "-->从服务器获取Person数据\n");
41             Person person = GsonTools.getPerson(response, Person.class);
42             addTextToView(view, "姓名:" + person.getName() + "\n年龄:" + person.getAge() + "\n地址:" + person.getAddress());
43             break;
44         case R.id.persons_result:
45             addTextToView(view, "-->从服务器获取List<Person>数据\n");
46             List<Person> persons = GsonTools.getPersons(response, Person[].class);
47             for (int i = 0; i < persons.size(); i++) {
48                 Person p = persons.get(i);
49                 addTextToView(view, "-第" + (i + 1) + "条数据\n");
50                 addTextToView(view, "姓名:" + p.getName() + "\n年龄:" + p.getAge() + "\n地址:" + p.getAddress());
51                 if (i != persons.size() - 1) {
52                     addTextToView(view, "\n");
53                 }
54             }
55             break;
56         case R.id.strings_result:
57             addTextToView(view, "-->从服务器获取List<String>数据\n");
58             List<String> strings = GsonTools.getStrings(response);
59             for (int i = 0; i < strings.size(); i++) {
60                 addTextToView(view, strings.get(i));
61                 if (i != strings.size() - 1) {
62                     addTextToView(view, " -> ");
63                 }
64             }
65             break;
66         case R.id.maps_result:
67             addTextToView(view, "-->从服务器获取List<HashMap<String,Object>>数据\n");
68             List<HashMap<String, String>> maps = GsonTools.getMaps(response, String.class);
69             for (int i = 0; i < maps.size(); i++) {
70                 addTextToView(view, "-第" + (i + 1) + "条数据:\n");
71                 addTextToView(view, "姓名:" + maps.get(i).get("name").toString() + "\n");
72                 addTextToView(view, "电话:" + maps.get(i).get("phone").toString() + "\n");
73                 addTextToView(view, "地址:" + maps.get(i).get("address").toString());
74                 if (i != maps.size() - 1) {
75                     addTextToView(view, "\n");
76                 }
77             }
78             break;
79         }
80     }
81 
82     // 向指定TextView中添加文本
83     private void addTextToView(TextView view, String text) {
84         String currentText = view.getText().toString();
85         currentText += text;
86         view.setText(currentText);
87     }
88 
89     @Override
90     protected void onStop() {
91         super.onStop();
92         MyApplication.getRequestQueue().cancelAll("GsonPerson");
93         MyApplication.getRequestQueue().cancelAll("GsonPersons");
94         MyApplication.getRequestQueue().cancelAll("GsonStrings");
95         MyApplication.getRequestQueue().cancelAll("GsonMaps");    }
96 }
主界面MainActivity中的代码

运行结果如下图:

 

三、FastJSON的封装和解析

服务端 的代码和使用GSON解析时的服务端代码相同(不需要改变任何东西,包括JAR包)。

客户端 的代码如下:

在解析FastJSON时,客户端需要导入解析FastJSON所需要的JAR包(点击这里下载)。

 1 public class FastJsonTools {
 2     public static <T> T getPerson(String jsonString, Class<T> cls) {
 3         T t = null;
 4         try {
 5             t = JSON.parseObject(jsonString, cls);
 6         } catch (Exception e) {
 7             e.printStackTrace();
 8         }
 9         return t;
10     }
11 
12     // 解析List<Person>数据和List<String>数据都使用这个方法
13     public static <T> List<T> getPersons(String jsonString, Class<T> cls) {
14         List<T> list = null;
15         try {
16             list = JSON.parseArray(jsonString, cls);
17         } catch (Exception e) {
18             e.printStackTrace();
19         }
20         return list;
21     }
22 
23     public static List<HashMap<String, Object>> getMaps(String jsonString) {
24         List<HashMap<String, Object>> maps = new ArrayList<HashMap<String, Object>>();
25         try {
26             maps = JSON.parseObject(jsonString, new TypeReference<List<HashMap<String, Object>>>() {
27             });
28         } catch (Exception e) {
29             e.printStackTrace();
30         }
31         return maps;
32     }
33 }
处理收到的数据的工具类
 1 public class MainActivity extends Activity {
 2     private final String url = "http://192.168.1.102:8080/GsonServer/GsonServlet";
 3     private TextView person_result, persons_result, strings_result, maps_result;
 4 
 5     @Override
 6     protected void onCreate(Bundle savedInstanceState) {
 7         super.onCreate(savedInstanceState);
 8         setContentView(R.layout.activity_main);
 9         person_result = (TextView) findViewById(R.id.person_result);
10         persons_result = (TextView) findViewById(R.id.persons_result);
11         strings_result = (TextView) findViewById(R.id.strings_result);
12         maps_result = (TextView) findViewById(R.id.maps_result);
13 
14         getResultToView(url + "?key=person", "FastJsonPerson", person_result);
15         getResultToView(url + "?key=persons", "FastJsonPersons", persons_result);
16         getResultToView(url + "?key=strings", "FastJsonStrings", strings_result);
17         getResultToView(url + "?key=maps", "FastJsonMaps", maps_result);
18     }
19 
20     private void getResultToView(String url, String tag, final TextView view) {
21         StringRequest request = new StringRequest(Method.GET, url, new Listener<String>() {
22             @Override
23             public void onResponse(String response) {
24                 manageResponse(view, response);
25             }
26         }, new Response.ErrorListener() {
27             @Override
28             public void onErrorResponse(VolleyError arg0) {
29                 addTextToView(view, arg0.toString());
30             }
31         });
32         request.setTag(tag);
33         MyApplication.getRequestQueue().add(request);
34     }
35 
36     private void addTextToView(TextView view, String text) {
37         String currentText = view.getText().toString();
38         currentText += text;
39         view.setText(currentText);
40     }
41 
42     private void manageResponse(TextView view, String response) {
43         switch (view.getId()) {
44         case R.id.person_result:
45             addTextToView(view, "-->从服务端获取Person数据\n");
46             Person person = FastJsonTools.getPerson(response, Person.class);
47             addTextToView(view,
48                     "姓名:" + person.getName() + "\n年龄:" + person.getAddress() + "\n地址:" + person.getAddress());
49             break;
50         case R.id.persons_result:
51             addTextToView(view, "-->从服务器获取List<Person>数据\n");
52             List<Person> persons = FastJsonTools.getPersons(response, Person.class);
53             for (int i = 0; i < persons.size(); i++) {
54                 Person p = persons.get(i);
55                 addTextToView(view, "-第" + (i + 1) + "条数据\n");
56                 addTextToView(view, "姓名:" + p.getName() + "\n年龄:" + p.getAge() + "\n地址:" + p.getAddress());
57                 if (i != persons.size() - 1) {
58                     addTextToView(view, "\n");
59                 }
60             }
61             break;
62         case R.id.strings_result:
63             addTextToView(view, "-->从服务器获取List<String>数据\n");
64             List<String> strings = FastJsonTools.getPersons(response, String.class);
65             for (int i = 0; i < strings.size(); i++) {
66                 addTextToView(view, strings.get(i));
67                 if (i != strings.size() - 1) {
68                     addTextToView(view, " -> ");
69                 }
70             }
71             break;
72         case R.id.maps_result:
73             addTextToView(view, "-->从服务器获取List<HashMap<String,Object>>数据\n");
74             List<HashMap<String, Object>> maps = FastJsonTools.getMaps(response);
75             for (int i = 0; i < maps.size(); i++) {
76                 addTextToView(view, "-第" + (i + 1) + "条数据:\n");
77                 addTextToView(view, "姓名:" + maps.get(i).get("name").toString() + "\n");
78                 addTextToView(view, "电话:" + maps.get(i).get("phone").toString() + "\n");
79                 addTextToView(view, "地址:" + maps.get(i).get("address").toString());
80                 if (i != maps.size() - 1) {
81                     addTextToView(view, "\n");
82                 }
83             }
84             break;
85         }
86     }
87 
88     @Override
89     protected void onStop() {
90         super.onStop();
91         MyApplication.getRequestQueue().cancelAll("FastJsonPerson");
92         MyApplication.getRequestQueue().cancelAll("FastJsonPersons");
93         MyApplication.getRequestQueue().cancelAll("FastJsonStrings");
94         MyApplication.getRequestQueue().cancelAll("FastJsonMaps");
95     }
96 }
主界面MainActiivty中的代码

运行结果如下图:

posted @ 2016-02-16 20:44  小挂坠  阅读(2714)  评论(0编辑  收藏  举报