歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android入門:通過JSON數據與服務器進行通信

Android入門:通過JSON數據與服務器進行通信

日期:2017/3/1 10:17:41   编辑:Linux編程

我們完成“Android入門:通過JSON數據與服務器進行通信“同樣的功能,只是數據傳輸使用JSON而不是XML;

注意點:

(1)當返回JSON時,content-type為text/json;

(2)通過JSON包進行解析JSON格式數據和生成JSON格式數據;

(3)Android中已經集成了JSON的包;

相關閱讀:Android入門:通過XML數據與服務器進行通信 http://www.linuxidc.com/Linux/2012-07/64597.htm


一、核心代碼介紹


服務器端核心代碼:


(1)JSONStringer stringer = new JSONStringer();

(2)stringer.array().endArray();

(3)stringer.object().key("key").value("value").endObject();

(4)String str = stringer.toString();


客戶端核心代碼:

(1)JSONArray array = new JSONArray(String str); //將字符串轉為JSONArray格式

(2)JSONObject object = array.getJSONObject(int index);

(3)int value = object.getInt(String name);

(4)String value = object.getString(String name);


二、全部代碼


服務器端:

ListServlet.java

  1. package org.xiazdong.servlet;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.annotation.WebServlet;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import org.json.JSONStringer;
  11. import org.xiazdong.domain.Person;
  12. @WebServlet("/ListServlet")
  13. public class ListServlet extends HttpServlet {
  14. private static final long serialVersionUID = 1L;
  15. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  16. doPost(request,response);
  17. }
  18. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  19. List<Person> list = new ArrayList<Person>();
  20. for(int i=0;i<4;i++){
  21. Person person = new Person(i,"xiazdong-"+i,20+i);
  22. list.add(person);
  23. }
  24. //將List<Person>組織成JSON字符串
  25. JSONStringer stringer = new JSONStringer();
  26. try{
  27. stringer.array();
  28. for(Person person:list){
  29. stringer.object().key("id").value(person.getId()).key("name").value(person.getName()).key("age").value(person.getAge()).endObject();
  30. }
  31. stringer.endArray();
  32. }
  33. catch(Exception e){}
  34. response.getOutputStream().write(stringer.toString().getBytes("UTF-8"));
  35. response.setContentType("text/json; charset=UTF-8"); //JSON的類型為text/json
  36. }
  37. }

在浏覽器中訪問效果如下:


客戶端:


MainActivity.java

  1. package org.xiazdong.personlist;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11. import org.json.JSONArray;
  12. import org.json.JSONObject;
  13. import org.xiazdong.domain.Person;
  14. import org.xmlpull.v1.XmlPullParser;
  15. import android.app.Activity;
  16. import android.os.Bundle;
  17. import android.util.Log;
  18. import android.util.Xml;
  19. import android.widget.ListView;
  20. import android.widget.SimpleAdapter;
  21. public class MainActivity extends Activity {
  22. private ListView listView;
  23. @Override
  24. public void onCreate(Bundle savedInstanceState) {
  25. super.onCreate(savedInstanceState);
  26. setContentView(R.layout.main);
  27. listView = (ListView) this.findViewById(R.id.listview);
  28. List<Person> persons = null;
  29. try {
  30. persons = getJSONData();
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. }
  34. List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
  35. for (Person person : persons) {
  36. HashMap<String, Object> map = new HashMap<String, Object>();
  37. map.put("id", person.getId());
  38. map.put("name", person.getName());
  39. map.put("age", person.getAge());
  40. maps.add(map);
  41. }
  42. SimpleAdapter adapter = new SimpleAdapter(this, maps, R.layout.item,
  43. new String[] { "id", "name", "age" }, new int[] { R.id.id,
  44. R.id.name, R.id.age });
  45. listView.setAdapter(adapter);
  46. }
  47. //讀取JSON數據並轉為List<Person>
  48. private List<Person> getJSONData() throws Exception {
  49. List<Person> persons = new ArrayList<Person>();
  50. URL url = new URL("http://192.168.0.103:8080/Server/ListServlet");
  51. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  52. conn.setRequestMethod("GET");
  53. if (conn.getResponseCode() == 200) {
  54. InputStream in = conn.getInputStream();
  55. persons = parseJSON(in);
  56. }
  57. return persons;
  58. }
  59. private List<Person> parseJSON(InputStream in)throws Exception{
  60. List<Person> persons = new ArrayList<Person>();
  61. Person person = null;
  62. String str = read(in);
  63. JSONArray array = new JSONArray(str);
  64. int length = array.length();
  65. for(int i=0;i<length;i++){
  66. JSONObject object = array.getJSONObject(i);
  67. person = new Person(object.getInt("id"), object.getString("name"), object.getInt("age"));
  68. persons.add(person);
  69. }
  70. return persons;
  71. }
  72. private String read(InputStream in) throws IOException {
  73. byte[] data;
  74. ByteArrayOutputStream bout = new ByteArrayOutputStream();
  75. byte[]buf = new byte[1024];
  76. int len = 0;
  77. while((len = in.read(buf))!=-1){
  78. bout.write(buf, 0, len);
  79. }
  80. data = bout.toByteArray();
  81. return new String(data,"UTF-8");
  82. }
  83. }

總結:

JSON和XML都是數據傳輸的兩種格式;

Copyright © Linux教程網 All Rights Reserved