Android入门:通过JSON数据与服务器进行通信
2012-07-06 22:37:38 来源:WEB开发网核心提示: 注意点:(1)当返回JSON时,content-type为text/json;(2)通过JSON包进行解析JSON格式数据和生成JSON格式数据;一、核心代码介绍服务器端核心代码:(1)JSONStringer stringer = new JSONStringer();(2)stringer.array().end
注意点:
(1)当返回JSON时,content-type为text/json;
(2)通过JSON包进行解析JSON格式数据和生成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"); } }
- ››Android 当修改一些代码时,使用什么编译命令可以最...
- ››Android 如何添加一个apk使模拟器和真机都编译进去...
- ››Android 修改Camera拍照的默认保存路径
- ››Android 如何修改默认输入法
- ››android开发中finish()和System.exit(0)的区别
- ››Android手势识别简单封装类
- ››android中查看项目数字证书的两种方法
- ››Android中获取IMEI码的办法
- ››android 相机报错 setParameters failed
- ››Android重启运用程序的代码
- ››Android为ListView的Item设置不同的布局
- ››android bitmap与base64字符串的互相转换
更多精彩
赞助商链接