Android网络开发中如何使用JSON进行网络通信---Android JSON数据通讯方法解析 ?
在开发客户端与服务端的应用当中,数据交换接口通常都是通过XML格式来进行数据交换的。近年来,随着AJAX技术的兴起,JSON作为一种轻量级的数据交换格式,以其易于阅读和编写的优点,也越来越多的被使用到各个项目中。本文将快速讲解 JSON 格式,并通过代码示例演示如何分别在客户端和服务器端进行 JSON 格式数据的处理。
什么是JSON ?
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于阅读和编写,同时也易于机器解析和生成,非常适合于服务器与客户端的交互。JSON采用与编程语言无关的文本格式,但是也使用了类C语言的习惯,这些特性使JSON成为理想的数据交换格式。 和 XML 一样,JSON 也是基于纯文本的数据格式。好了,Json就暂时讲解到这里,有兴趣的朋友可以上网下载一些专业的资料进行学习。
实例中都有什么?
实例中包含Android的客户端和Web服务端。对于没有接触过服务器开发的朋友也不必担心,您完全可以跳过Web端,因为在开发过程中,会有专门的人来写Web端,你所要做的只是了解一下通讯协议,接收服务端的返回数据,或者发送数据到服务端即可。至于服务端是怎样实现的你完全不用理会。
以下是实例代码:代码我已经测试过了,如果看不懂的朋友只需复制粘贴到项目中即可。
要运行本实例都需要那些工具包 ?
客户端:gson.jar 到code.google.com/p/google-gson/下载jar包。此包为google提供,专门用于解析json。
服务端:就是用于解析json的一系列jar包,上网百度一下就出来了。呵呵……
一、客户端
1.JsonActivity.java
package com.example.myapi.json; import java.util.List; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.widget.TextView; import com.example.myapi.R; /* * * @author 利用json进行数据传输 * */ public class JsonActivity extends Activity{ public static final int RESULT=111111; private TextView tvId; private List<Entity> list = null; public String data = null; public JsonThread json ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.json); tvId = (TextView)findViewById(R.id.json_tv_id); json = new JsonThread(); new Thread(json).start(); } class JsonThread implements Runnable{ public void run() { try { data = HttpUtils.getInstance().getData("http://10.0.2.2:8080/JsonWeb/HttpServletDemo"); if(data != null){ Log.e("data not null", data.toString()); } handler.sendEmptyMessage(RESULT); Log.e("data", "nullljsdflsdf"); } catch (Exception e) { e.printStackTrace(); Log.e("JsonThread", e.getMessage()); } } public String getData(){ return data; } } Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { switch(msg.what){ case RESULT: data = json.getData(); list = JsonUtils.parseEntityFromJson(data); for(Entity entity:list){ data += "name: " + entity.getTestName() + " " + "age: " + entity.getTestAge() + " " + "id: " + entity.getTestId() + "\n"; } Log.e("data", ""+data.toString()); tvId.setText(data); break; } }; }; }
2.JsonUtils.java 解析json的工具
package com.example.myapi.json; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * 用于解析json的工具类 * @author tony * */ public class JsonUtils { private JsonUtils(){} public static List<Entity> parseEntityFromJson(String data){ Type listType = (Type) new TypeToken<ArrayList<Entity>>() {}.getType(); Gson gson = new Gson(); ArrayList<Entity> list = gson.fromJson(data,listType); return list; } }
3.HttpUtils.java处理Http的工具类
package com.example.myapi.json; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; /** * Http工具类 * @author tony * */ public class HttpUtils { private HttpUtils(){} private static HttpUtils instance = null; public static HttpUtils getInstance(){ if(instance == null){ synchronized(HttpUtils.class){ instance = new HttpUtils(); } } return instance; } /** * 返回从服务器端获取到的数据 * @param url * @return */ public String getData(String url)throws Exception{ StringBuffer sb = new StringBuffer(); HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse response = httpClient.execute(httpGet); HttpEntity httpEntity = response.getEntity(); if(httpEntity != null){ InputStream in = httpEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while((line= reader.readLine())!=null){ sb.append(line); } } return sb.toString(); } }
3.Entity.java项目中用到的实体类
package com.example.myapi.json; public class Entity { private String testId; public Entity() { super(); } public Entity(String testId, String testName, String testAge) { super(); this.testId = testId; this.testName = testName; this.testAge = testAge; } public String getTestId() { return testId; } public void setTestId(String testId) { this.testId = testId; } public String getTestName() { return testName; } public void setTestName(String testName) { this.testName = testName; } public String getTestAge() { return testAge; } public void setTestAge(String testAge) { this.testAge = testAge; } private String testName; private String testAge; }
二、服务器端
1. HttpServletDemo.java
package cn.web.demo; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class HttpServletDemo extends HttpServlet{ private static final long serialVersionUID = 5451751100000L; private List<Entity> list; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.setCharacterEncoding("utf-8"); PrintWriter writer = resp.getWriter(); prepareData(); //Json数组 JSONArray array = new JSONArray(); for(Entity entity : list){ JSONObject object = new JSONObject(); object.put("id", entity.getTestId()); object.put("name", entity.getTestName()); object.put("age", entity.getTestAge()); array.add(object); } writer.write(array.toString()); writer.flush(); writer.close(); } /** * 准备数据 */ private void prepareData(){ list = new ArrayList<Entity>(); Entity entity = new Entity(); entity.setTestId("123456789"); entity.setTestName("南风博文"); entity.setTestAge("22"); list.add(entity); Entity entity1 = new Entity(); entity1.setTestId("789644313132"); entity1.setTestName("小萝莉"); entity1.setTestAge("16"); list.add(entity1); Entity entity2 = new Entity(); entity2.setTestId("asdfasdf"); entity2.setTestName("tony"); entity2.setTestAge("22"); list.add(entity2); } }
2.Entity.java服务端的实体类
package cn.web.demo; public class Entity { private String testId; public Entity() { super(); } public Entity(String testId, String testName, String testAge) { super(); this.testId = testId; this.testName = testName; this.testAge = testAge; } public String getTestId() { return testId; } public void setTestId(String testId) { this.testId = testId; } public String getTestName() { return testName; } public void setTestName(String testName) { this.testName = testName; } public String getTestAge() { return testAge; } public void setTestAge(String testAge) { this.testAge = testAge; } private String testName; private String testAge; }
3.web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>HttpServletDemo</servlet-name> <servlet-class>cn.web.demo.HttpServletDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>HttpServletDemo</servlet-name> <url-pattern>/HttpServletDemo</url-pattern> </servlet-mapping> </web-app>
备注:本实例只写了客户端从服务器端获取数据。而并没有写客户端向服务器发送数据。