Android JSONGSONFastJson的封装与解析
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android JSONGSONFastJson的封装与解析相关的知识,希望对你有一定的参考价值。
声明:
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 }
一、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 }
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 }
对于输入的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>
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 }
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 }
运行结果如下图所示:
二、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 }
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 }
对于输入的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
以上是关于Android JSONGSONFastJson的封装与解析的主要内容,如果未能解决你的问题,请参考以下文章
Android 逆向Android 权限 ( Android 逆向中使用的 android.permission 权限 | Android 系统中的 Linux 用户权限 )