https://www.cnblogs.com/sunnywindycloudy/p/8343013.html
原文地址:http://blog.csdn.net/whx405831799/article/details/42171191
给服务端发送请求后,服务端会返回一连串的数据,这些数据在大部分情况下都是XML格式或者JSON格式。然后JSON相对XML来说解析相对方便一些,所以先说说JSON的解析。
JSON的基本数据格式有这几种:
1.一个JSON对象——JSONObject
{"name":"胡小威" , "age":20 , "male":true}
2.一个JSON数组——JSONArray
[{"name":"胡小威" , "age":20 , "male":true},{"name":"赵小亮" , "age":22 , "male":false}]
3.复杂一点的JSONObject
{"name":"胡小威", "age"=20, "male":true, "address":{"street":"岳麓山南", "city":"长沙","country":"中国"}}
4.复杂一点的JSONArray
[
{"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.{"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; }
这里我只是简单获取了几个我想要的数据。
二、使用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()); }