本文讲解android解析json数据。客户端接收服务端发来的4种json数据,分别解析成四种类型Person , List<Person> , List<String> , List<Map<String,Object>>,从MainActivity传递到OtherActivity.
接收的服务器端的4种json数据分别为:
1. {"person":{"address":"香港","id":1001,"name":"刘德华"}}
2. {"persons":[{"address":"香港","id":1001,"name":"刘德华"},{"address":"韩国","id":1001,"name":"宋慧乔"}]}
3. {"listString":["美国","中国","俄罗斯"]}
4. {"listMap":[{"id":1001,"address":"香港","name":"刘德华"},{"id":1002,"address":"韩国","name":"宋慧乔"}]}
客户端相应4种操作 :
1. MainActivity 将json数据解析成Person类,用Intent将Peson对象传递给OtherActvity. 设置标记click_flag = person
2. MainActivity 将json数据解析成List<Person>,用Intent将List<Person>传递给OtherActvity. 设置标记click_flag = persons
3. MainActivity 将json数据解析成List<String>,用Intent将List<String>传递给OtherActvity. 设置标记click_flag = listString
4. MainActivity 将json数据解析成List<Map<String,Object>>,用Intent将List<Map<String,Object>>传递给OtherActvity. 设置标记click_flag = listMap
----------------------------------------------------------------------------------------------------------------------------------
三点重点注意点:
1. 在AndroidManifest.xml中 加上
<!-- 添加访问网络的授权 -->
<uses-permission android:name="android.permission.INTERNET" />
2. android中Http访问时 connection.getResponseCode()不被执行 。添加访问网络的授权后,仍不能执行
3. 在android的两个activity中,如何用Intent传递Person对象,List<Person>,List<Map<String,Object>>类型。
一.Intent 传递 Person对象
传递 intent.putExtra("person", (Serializable)person);
接收 Person person =(Person) intent.getSerializableExtra("person");
二.Intent 传递 List<Person>对象
传递 intent.putExtra("persons", (Serializable) list);
接收 List<Person> list = (List<Person>) intent.getSerializableExtra("persons");
三. Intent传递 List<Map<String,Object>>类型
传递 intent.putExtra("listMap", (Serializable) list);
接收 List<Map<String, Object>> list = (List<Map<String, Object>>) intent.getSerializableExtra("listMap");
注意:Intent 传递的对象object必须都实现Serializable接口,List<Object>内的object也必须要实现Serializable接口.
-------------------------------------------------------------------------------------------------------------------------------
1.点击“解析person数据”,反馈结果如下:
2. 点击“解析persons数据”,反馈结果如下:
3. 点击“解析listString数据”,反馈结果如下:
4.点击“解析listMap数据”,反馈结果如下:
----------------------------------------------------------------------------------------------------------------------
程序思路:
1.服务器端产生4种类型的json数据,客户端android用GET方式分别获取服务器端返回的json数据,http 请求传递参数action_flag. 服务器端根据action_flag 返回不同的json数据给客户端。
2.客户端将4种不同的json数据解析成4中不同的结果类型(Person,List<Person>,List<String>,List<Map<String,Object>>),用Intent方式由MainActivity传递给OtherActivity,在OtherActvity中显示解析的结果。
----------------------------------------------------------------------------------------------------------------------
客户端android工程目录(左)和服务器端web工程目录(右)
1. AndroidManifest.xml 加上网络访问权限
<!-- 添加访问网络的授权 -->
<uses-permission android:name="android.permission.INTERNET" />
2.activity_main.xml 主机面
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">" <Button android:id="@+id/person" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="解析Person数据" /> <Button android:id="@+id/persons" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="解析Persons数据" /> <Button android:id="@+id/listString" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="解析listString数据" /> <Button android:id="@+id/listMap" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="解析listMap数据" /> </LinearLayout>
3. avtivity_other.xml 点击主界面的按钮后相应的界面
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/msg" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
4.MainActivity.java
package com.android.myjson; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.json.data.Person; import com.json.http.HttpUtils; import com.json.tools.JsonTools; import android.os.Bundle; import android.os.StrictMode; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity implements OnClickListener { private Button person, persons, listString, listMap; private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); closeStrictMode(); person = (Button) findViewById(R.id.person); persons = (Button) findViewById(R.id.persons); listString = (Button) findViewById(R.id.listString); listMap = (Button) findViewById(R.id.listMap); person.setOnClickListener(this); persons.setOnClickListener(this); listString.setOnClickListener(this); listMap.setOnClickListener(this); } @Override public void onClick(View v) { String url_path = ""; String jsonString = ""; switch (v.getId()) { case R.id.person: url_path = "http://192.168.0.102:8080/json_Project/servlet/JsonAction?action_flag=person"; jsonString = HttpUtils.getJsonContent(url_path, "utf-8"); Person person = JsonTools.getPerson("person", jsonString); Intent intent = new Intent(MainActivity.this, OtherActivity.class); intent.putExtra("click_flag", "person"); // 标记当前intent是按钮 person intent.putExtra("person", (Serializable)person); startActivity(intent); break; case R.id.persons: url_path = "http://192.168.0.102:8080/json_Project/servlet/JsonAction?action_flag=persons"; jsonString = HttpUtils.getJsonContent(url_path, "utf-8"); try { List<Person> list = JsonTools.getPersons("persons", jsonString); Intent intent2 = new Intent(MainActivity.this, OtherActivity.class); intent2.putExtra("click_flag", "persons"); // 标记当前intent按钮是persons intent2.putExtra("persons", (Serializable) list); startActivity(intent2); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case R.id.listString: url_path = "http://192.168.0.102:8080/json_Project/servlet/JsonAction?action_flag=listString"; jsonString = HttpUtils.getJsonContent(url_path, "utf-8"); List<String> list = new ArrayList<String>(); try { list = (ArrayList<String>) JsonTools.getListString( "listString", jsonString); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Intent intent2 = new Intent(this, OtherActivity.class); intent2.putExtra("click_flag", "listString"); // 标记 // 当前intent按钮是listString intent2.putStringArrayListExtra("listString", (ArrayList<String>) list); // 参数中的list要加强制转换 startActivity(intent2); break; case R.id.listMap: url_path = "http://192.168.0.102:8080/json_Project/servlet/JsonAction?action_flag=listMap"; jsonString = HttpUtils.getJsonContent(url_path, "utf-8"); List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>(); try { list2 = JsonTools.getListMap("listMap", jsonString); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Intent intent3 = new Intent(MainActivity.this, OtherActivity.class); intent3.putExtra("click_flag", "listMap"); // 标记 当前intent按钮是listMap // 用Intent传递List<Map<String,Object>> 对象,其中HashMap实现了Serializable intent3.putExtra("listMap", (Serializable) list2); startActivity(intent3); break; } } @SuppressLint("NewApi") public static void closeStrictMode() { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll().penaltyLog().build()); } }
5.OtherActivity.java
package com.android.myjson; import java.util.List; import java.util.Map; import com.json.data.Person; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; public class OtherActivity extends Activity { private TextView textView; public OtherActivity() { // TODO Auto-generated constructor stub } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_other); textView = (TextView) findViewById(R.id.msg); Intent intent = getIntent(); String click_flag = intent.getStringExtra("click_flag"); if ("person".equals(click_flag)) { // 如果是点击 person按钮 // 接收Intent传递的Person对象 Person person =(Person) intent.getSerializableExtra("person"); textView.setText(person.toString()); } else if ("persons".equals(click_flag)) {// 如果是点击 persons按钮 // 接收Intent传递的List<Person>参数 @SuppressWarnings("unchecked") List<Person> list = (List<Person>) intent .getSerializableExtra("persons"); String persons = ""; for (Person person : list) { persons += person.toString() + "\n"; } textView.setText(persons); } else if ("listString".equals(click_flag)) { List<String> list = (List<String>) intent .getStringArrayListExtra("listString"); String listString = ""; for (String s : list) { listString += s + "\n"; } textView.setText(listString); } else if ("listMap".equals(click_flag)) { //接收Intent传递的List<Map<String,Object>>参数 @SuppressWarnings("unchecked") List<Map<String, Object>> list = (List<Map<String, Object>>) intent .getSerializableExtra("listMap"); String listMapString = ""; for (Map<String, Object> map : list) { // 遍历一个Map for (Map.Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); listMapString += " " + key + " : " + value + " "; } listMapString += "\n"; } textView.setText(listMapString); } } }
6.Person.java
package com.json.data; import java.io.Serializable; public class Person implements Serializable { /** * */ private static final long serialVersionUID = 1L; private int id; private String name; private String address; public Person() { // TODO Auto-generated constructor stub } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Person(int id, String name, String address) { super(); this.id = id; this.name = name; this.address = address; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", address=" + address + "]"; } }
7.HttpUtils.java
package com.json.http; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.annotation.SuppressLint; import android.os.StrictMode; public class HttpUtils { public HttpUtils() { // TODO Auto-generated constructor stub } public static String getJsonContent(String url_path ,String encode){ String jsonString = ""; try { URL url = new URL(url_path); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setConnectTimeout(3000); connection.setRequestMethod("GET"); connection.setDoInput(true); //从服务器获得数据 int responseCode = connection.getResponseCode(); if (200 == responseCode) { jsonString = changeInputStream(connection.getInputStream(),encode); } } catch (Exception e) { // TODO: handle exception } // return jsonString; } private static String changeInputStream(InputStream inputStream , String encode) throws IOException { // TODO Auto-generated method stub String jsonString = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; while((len=inputStream.read(data))!=-1){ outputStream.write(data, 0, len); } jsonString = new String(outputStream.toByteArray(), encode); inputStream.close(); return jsonString; } }
8.JsonTools.java
package com.json.tools; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.json.data.Person; /** * 完成对json数据的解析 * * @author ben * */ public class JsonTools { private static final String TAG = "JsonTools"; public JsonTools() { // TODO Auto-generated constructor stub } public static Person getPerson(String key, String jsonString) { Person person = new Person(); try { // jsonObject ={"person":{"address":"香港","id":1001,"name":"刘德华"}} JSONObject jsonObject = new JSONObject(jsonString); // personObject = {"address":"香港","id":1001,"name":"刘德华"} JSONObject personObject = jsonObject.getJSONObject(key); // 此处key = "person" person.setId(personObject.getInt("id")); person.setName(personObject.getString("name")); person.setAddress(personObject.getString("address")); } catch (Exception e) { // TODO: handle exception } return person; } public static List<Person> getPersons(String key , String jsonString) throws Exception{ List<Person> list = new ArrayList<Person>(); //jsonObject={"persons":[{"address":"香港","id":1001,"name":"刘德华"},{"address":"韩国","id":1002,"name":"宋慧乔"}]} JSONObject jsonObject = new JSONObject(jsonString); //jsonArray =[{"address":"香港","id":1001,"name":"刘德华"},{"address":"韩国","id":1002,"name":"宋慧乔"}] JSONArray jsonArray = jsonObject.getJSONArray(key); //此处key = persons,取得 for (int i = 0; i < jsonArray.length(); i++) { JSONObject personObject = jsonArray.getJSONObject(i); Person person = new Person(); person.setId(personObject.getInt("id")); person.setName(personObject.getString("name")); person.setAddress(personObject.getString("address")); list.add(person); } return list; } public static List<String> getListString(String key,String jsonString) throws Exception{ List<String> list = new ArrayList<String>(); // jsonObject = {"listString":["美国","中国","俄罗斯"]} JSONObject jsonObject = new JSONObject(jsonString); // jsonArray = ["美国","中国","俄罗斯"] JSONArray jsonArray = jsonObject.getJSONArray(key); for (int i =0 ; i<jsonArray.length();i++) { String s = jsonArray.getString(i); list.add(s); } return list; } public static List<Map<String, Object>> getListMap(String key , String jsonString) throws Exception{ List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); JSONObject jsonObject = new JSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray(key); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject2 = jsonArray.getJSONObject(i); Map<String, Object> map = new HashMap<String, Object>(); //重点:如何遍历json 对象中的key Iterator<String> iterator = jsonObject2.keys(); // 获取json对象中的key,返回一个string集合。 while(iterator.hasNext()){ String json_key = iterator.next(); Object json_value = jsonObject2.get(json_key); if (json_value == null) { //因为JSON value可为 null; json_value = ""; } map.put(json_key, json_value); } list.add(map); } return list; } }
服务器端 json_Project
1.JsonAction.java
package com.json.action; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.json.service.JsonService; import com.json.tools.JsonTools; public class JsonAction extends HttpServlet { JsonService jsonService ; /** * Constructor of the object. */ public JsonAction() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); // 获取 person的 list , 保存为json数据 // String jsonString = JsonTools.creatJsonString("persons", jsonService.getListPersons()); String jsonString =""; String action_flag = request.getParameter("action_flag"); if ("person".equals(action_flag)) { jsonString = JsonTools.creatJsonString("person", jsonService.getPerson()); } else if("persons".equals(action_flag)) { jsonString = JsonTools.creatJsonString("persons", jsonService.getListPersons()); }else if("listString".equals(action_flag)) { jsonString = JsonTools.creatJsonString("listString", jsonService.getListString()); }else if("listMap".equals(action_flag)) { jsonString = JsonTools.creatJsonString("listMap", jsonService.getListMap()); } out.println(jsonString); System.out.println("jsonString"+jsonString); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here jsonService = new JsonService(); } }
2.Person.java
package com.json.data; public class Person { private int id; private String name; private String address; public Person() { // TODO Auto-generated constructor stub } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Person(int id, String name, String address) { super(); this.id = id; this.name = name; this.address = address; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", address=" + address + "]"; } }
3.JsonService.java
package com.json.service; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.List; import com.json.data.Person; public class JsonService { public JsonService() { // TODO Auto-generated constructor stub } public static Person getPerson() { Person person = new Person(1001, "刘德华", "香港"); return person; } public static List<Person> getListPersons() { List<Person> persons = new ArrayList<Person>(); Person person1 = new Person(1001, "刘德华", "香港"); Person person2 = new Person(1002, "宋慧乔", "韩国"); persons.add(person1); persons.add(person2); return persons; } public static List<String> getListString(){ List<String> list = new ArrayList<String>(); list.add("美国"); list.add("中国"); list.add("俄罗斯"); return list; } public static List<java.util.Map<String, Object>> getListMap(){ List<java.util.Map<String, Object>> list = new ArrayList<Map<String,Object>>(); java.util.Map<String,Object> map1 = new HashMap<String,Object>(); map1.put("id",1001); map1.put("name","刘德华"); map1.put("address","香港"); java.util.Map<String,Object> map2 = new HashMap<String,Object>(); map2.put("id",1002); map2.put("name","宋慧乔"); map2.put("address","韩国"); list.add(map1); list.add(map2); return list; } }
4.TestJson.java
package com.json.test; import com.json.service.JsonService; import com.json.tools.JsonTools; public class TestJson { public TestJson() { // TODO Auto-generated constructor stub } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //Test1 Person System.out.println("Json数据格式测试结果:\n"); String jsonString1 = JsonTools.creatJsonString("person", JsonService.getPerson()); //Test2 persons String jsonString2 = JsonTools.creatJsonString("persons", JsonService.getListPersons()); //Test3 listString String jsonString3 = JsonTools.creatJsonString("listString",JsonService.getListString()); //Test 4 listMap String jsonString4 = JsonTools.creatJsonString("listMap",JsonService.getListMap()); System.out.println("测试结果1:"+jsonString1+"\n"); System.out.println("测试结果2:"+jsonString2+"\n"); System.out.println("测试结果3:"+jsonString3+"\n"); System.out.println("测试结果4:"+jsonString4); } }
5.JsonTools.java
package com.json.tools; import net.sf.json.JSONObject; public class JsonTools { /** * @param key 表示json字符串的头信息 * @param value 表示解析几何的类型 * @return */ public static String creatJsonString(String key, Object value) { JSONObject jsonObject = new JSONObject(); jsonObject.put(key, value); return jsonObject.toString(); } }