轉自:http://www.javashuo.com/article/p-opahcopi-cz.htmlhtml
給服務端發送請求後,服務端會返回一連串的數據,這些數據在大部分狀況下都是XML格式或者JSON格式。而後JSON相對XML來講解析相對方便一些,因此先說說JSON的解析。json
JSON的基本數據格式有這幾種:數組
1.一個JSON對象——JSONObjectgoogle
{"name":"胡小威" , "age":20 , "male":true}spa
2.一個JSON數組——JSONArraycode
[{"name":"胡小威" , "age":20 , "male":true},{"name":"趙小亮" , "age":22 , "male":false}]htm
3.複雜一點的JSONObject對象
{"name":"胡小威", "age"=20, "male":true, "address":{"street":"嶽麓山南", "city":"長沙","country":"中國"}}blog
4.複雜一點的JSONArrayip
[
{"name":"胡小威", "age"=20, "male":true, "address":{"street":"嶽麓山南", "city":"長沙","country":"中國"}},
{"name":"趙小亮", "age"=22, "male":false, "address":{"street":"九州港", "city":"珠海","country":"中國"}}
]
5.來個更復雜的,這是我從愛幫公交上扒取的數據
{"buses":{"bus":[{"last_foot_dist":"0","time":"37","segments":{"segment":[{"line_name":"立珊專線(中南大學學生公寓-長沙火車站)","foot_dist":"362","stat_xys":"","stats":"嶽麓山南;湖南師大;二里半;嶽麓山北;市四醫院;華圖教育(太平街口);牛耳教育(南陽街口);韭菜園;曙光路口;長島路口;長沙火車站","end_stat":"長沙火車站","line_xys":"","line_dist":"7535","start_stat":"嶽麓山南"}]},"foot_dist":"362","dist":"7897"},{"last_foot_dist":"0","time":"41","segments":{"segment":[{"line_name":"旅1路(科教新村-長沙火車站)","foot_dist":"337","stat_xys":"","stats":"嶽麓山南;湖南師大;二里半;嶽麓山北;市四醫院;華圖教育(太平街口);蔡鍔中路口;韭菜園;喬莊;曙光路口;長島路口;五一東村;車站路口;長沙火車站","end_stat":"長沙火車站","line_xys":"","line_dist":"7822","start_stat":"嶽麓山南"}]},"foot_dist":"337","dist":"8159"}]}}
接下來是解析部分
1、直接解析
1.{"name":"胡小威" , "age":20 , "male":true}
public void parseJsonObject(String json) { try { JSONObject jsonObject = new JSONObject(json); String name = jsonObject.getString("name"); int age = jsonObject.getInt("age"); boolean male = jsonObject.getBoolean("male"); //接下來該幹嗎幹嗎 } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
2.[{"name":"胡小威" , "age":20 , "male":true},{"name":"趙小亮" , "age":22 , "male":false}]
public void parseJSONArray(String json) { try { JSONArray jsonArray = new JSONArray(json); for (int i = 0; i < jsonArray.length(); i++) { jsonObject = jsonArray.getJSONObject(i); String name = jsonObject.getString("name"); int age = jsonObject.getInt("age"); boolean male = jsonObject.getBoolean("male"); //接下來該幹嗎幹嗎 } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
3.{"name":"胡小威", "age"=20, "male":true, "address":{"street":"嶽麓山南", "city":"長沙","country":"中國"}}
public void parseJsonPerson(String json) { try { JSONObject jsonObject = new JSONObject(json); String name = jsonObject.getString("name"); int age = jsonObject.getInt("age"); boolean male = jsonObject.getBoolean("male"); JSONObject addressJSON = jsonObject.getJSONObject("address"); String street = addressJSON.getString("street"); String city = addressJSON.getString("city"); String country = addressJSON.getString("country"); Address address = new Address(street, city, country); Person person = new Person(name, age, male, address); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
4.
[
{"name":"胡小威", "age"=20, "male":true, "address":{"street":"嶽麓山南", "city":"長沙","country":"中國"}},
{"name":"趙小亮", "age"=22, "male":false, "address":{"street":"九州港", "city":"珠海","country":"中國"}}
]
public void parseJsonArrayPerson(String json) { List<Person> persons = new ArrayList<Person>(); try { jsonArray = new JSONArray(json); for (int i = 0; i < jsonArray.length(); i++) { jsonObject = jsonArray.getJSONObject(i); String name = jsonObject.getString("name"); int age = jsonObject.getInt("age"); boolean male = jsonObject.getBoolean("male"); JSONObject addressJSON = jsonObject.getJSONObject("address"); String street = addressJSON.getString("street"); String city = addressJSON.getString("city"); String country = addressJSON.getString("country"); Address address = new Address(street, city, country); Person person = new Person(name, age, male, address); persons.add(person); Log.v("juno", person.toString()); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.v("juno", persons.toString()); }
5. {"buses":{"bus":[{"last_foot_dist":"0","time":"37","segments":{"segment":[{"line_name":"立珊專線(中南大學學生公寓-長沙火車站)","foot_dist":"362","stat_xys":"","stats":"嶽麓山南;湖南師大;二里半;嶽麓山北;市四醫院;華圖教育(太平街口);牛耳教育(南陽街口);韭菜園;曙光路口;長島路口;長沙火車站","end_stat":"長沙火車站","line_xys":"","line_dist":"7535","start_stat":"嶽麓山南"}]},"foot_dist":"362","dist":"7897"},{"last_foot_dist":"0","time":"41","segments":{"segment":[{"line_name":"旅1路(科教新村-長沙火車站)","foot_dist":"337","stat_xys":"","stats":"嶽麓山南;湖南師大;二里半;嶽麓山北;市四醫院;華圖教育(太平街口);蔡鍔中路口;韭菜園;喬莊;曙光路口;長島路口;五一東村;車站路口;長沙火車站","end_stat":"長沙火車站","line_xys":"","line_dist":"7822","start_stat":"嶽麓山南"}]},"foot_dist":"337","dist":"8159"}]}}
public List<Salution> parseJSON(String str){ Log.d("返回的JSON數據:", str); List<Salution> busList = new ArrayList<Salution>(); try { JSONObject jsonObject = new JSONObject(str); JSONObject busesJSON = jsonObject.getJSONObject("buses"); JSONArray busJSArray=busesJSON.getJSONArray("bus"); for(int i=0;i<busJSArray.length();i++){ JSONObject busJSObject = busJSArray.getJSONObject(i); JSONObject segsJSObject=busJSObject.getJSONObject("segments"); JSONArray segJSArray=segsJSObject.getJSONArray("segment"); Salution st=new Salution(); for(int j=0;j<segJSArray.length();j++){ if(j==0){ JSONObject segJSObject = segJSArray.getJSONObject(j); st.setLine_name1(segJSObject.getString("line_name")); Log.d("line_name", segJSObject.getString("line_name")); st.setStats1(segJSObject.getString("stats")); st.setEnd_stat1(segJSObject.getString("end_stat")); st.setStart_stat1(segJSObject.getString("start_stat")); } if(j==1){ JSONObject segJSObject = segJSArray.getJSONObject(j); st.setLine_name2(segJSObject.getString("line_name")); Log.d("line_name", segJSObject.getString("line_name")); st.setStats2(segJSObject.getString("stats")); st.setEnd_stat2(segJSObject.getString("end_stat")); st.setStart_stat2(segJSObject.getString("start_stat")); } } busList.add(st); } return busList; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
這裏我只是簡單獲取了幾個我想要的數據。
2、使用JSON類庫Gson 來解析JSON
Gson 是 Google 提供的用來在 Java 對象和 JSON 數據之間進行映射的 Java 類庫。能夠將一個 JSON 字符串轉成一個 Java 對象,或者反過來。
首先,從 code.google.com/p/google-gson/downloads/list下載GsonAPI
google-gson-1.7.1-release.zip
再把gson-1.7.jar copy到libs
能夠使用兩種方法解析
①、經過獲取JsonReader對象解析JSON數據:
String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]"; try{ JsonReader reader = new JsonReader(new StringReader(jsonData)); reader.beginArray(); while(reader.hasNext()){ reader.beginObject(); while(reader.hasNext()){ String tagName = reader.nextName(); if(tagName.equals("username")){ System.out.println(reader.nextString()); } else if(tagName.equals("userId")){ System.out.println(reader.nextString()); } } reader.endObject(); } reader.endArray(); } catch(Exception e){ e.printStackTrace(); }
②、經過把JSON數據映射成一個對象,使用Gson對象的fromJson()方法獲取一個對象數組進行操做
Type listType = new TypeToken<LinkedList<User>>(){}.getType(); Gson gson = new Gson(); LinkedList<User> users = gson.fromJson(jsonData, listType); for (Iterator iterator = users.iterator(); iterator.hasNext();) { User user = (User) iterator.next(); System.out.println(user.getUsername()); System.out.println(user.getUserId()); }