1)当返回JSON时,content-type为text/json;
(2)通过JSON包进行解析JSON格式数据和生成JSON格式数据;
(3)Android中已经集成了JSON的包;
一、核心代码介绍
服务器端核心代码:
(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");
- }
- }