我們完成“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
- package org.xiazdong.servlet;
-
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
-
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import org.json.JSONStringer;
- import org.xiazdong.domain.Person;
-
-
- @WebServlet("/ListServlet")
- public class ListServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- doPost(request,response);
- }
-
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- List<Person> list = new ArrayList<Person>();
- for(int i=0;i<4;i++){
- Person person = new Person(i,"xiazdong-"+i,20+i);
- list.add(person);
- }
- //將List<Person>組織成JSON字符串
- JSONStringer stringer = new JSONStringer();
- try{
- stringer.array();
- for(Person person:list){
- stringer.object().key("id").value(person.getId()).key("name").value(person.getName()).key("age").value(person.getAge()).endObject();
- }
- stringer.endArray();
- }
- catch(Exception e){}
- response.getOutputStream().write(stringer.toString().getBytes("UTF-8"));
- response.setContentType("text/json; charset=UTF-8"); //JSON的類型為text/json
- }
-
- }
在浏覽器中訪問效果如下:
客戶端:
MainActivity.java
- package org.xiazdong.personlist;
-
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
-
- import org.json.JSONArray;
- import org.json.JSONObject;
- import org.xiazdong.domain.Person;
- import org.xmlpull.v1.XmlPullParser;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- import android.util.Xml;
- import android.widget.ListView;
- import android.widget.SimpleAdapter;
-
- public class MainActivity extends Activity {
- private ListView listView;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- listView = (ListView) this.findViewById(R.id.listview);
- List<Person> persons = null;
- try {
- persons = getJSONData();
- } catch (Exception e) {
- e.printStackTrace();
- }
- List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
- for (Person person : persons) {
- HashMap<String, Object> map = new HashMap<String, Object>();
- map.put("id", person.getId());
- map.put("name", person.getName());
- map.put("age", person.getAge());
- maps.add(map);
- }
- SimpleAdapter adapter = new SimpleAdapter(this, maps, R.layout.item,
- new String[] { "id", "name", "age" }, new int[] { R.id.id,
- R.id.name, R.id.age });
- listView.setAdapter(adapter);
- }
-
- //讀取JSON數據並轉為List<Person>
- private List<Person> getJSONData() throws Exception {
- List<Person> persons = new ArrayList<Person>();
- URL url = new URL("http://192.168.0.103:8080/Server/ListServlet");
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("GET");
- if (conn.getResponseCode() == 200) {
- InputStream in = conn.getInputStream();
- persons = parseJSON(in);
- }
- return persons;
-
- }
- private List<Person> parseJSON(InputStream in)throws Exception{
- List<Person> persons = new ArrayList<Person>();
- Person person = null;
- String str = read(in);
- JSONArray array = new JSONArray(str);
- int length = array.length();
- for(int i=0;i<length;i++){
- JSONObject object = array.getJSONObject(i);
- person = new Person(object.getInt("id"), object.getString("name"), object.getInt("age"));
- persons.add(person);
- }
- return persons;
- }
- private String read(InputStream in) throws IOException {
- byte[] data;
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- byte[]buf = new byte[1024];
- int len = 0;
- while((len = in.read(buf))!=-1){
- bout.write(buf, 0, len);
- }
- data = bout.toByteArray();
- return new String(data,"UTF-8");
- }
- }
總結:
JSON和XML都是數據傳輸的兩種格式;