android json數據解析

  • json數據結構

json中有兩種數據結構:對象和數組。java

 

對象android

  在JSON中,一個對象以「{」(左括號)開始,「}」(右括號)結束。每一個「名稱」後跟一個「:」(冒號),冒號後是該名稱的值,多個「名稱:值」之間使用 「,」(逗號)分隔開來。名稱須要使用雙引號括起來,值若是是字符串則必須用雙引號括起來,若是是數值型則不須要。json

 

以下的代碼是一個簡單的JSON對象示例:api

1   {
2   "id":001,
3   "name":"jack",
4   "age":25
5   }

 

數組數組

  在JSON中,數組是值(value)的有序集合。一個數組以「[」(左中括號)開始,「]」(右中括號)結束。值之間使用 「,」(逗號)分隔開來。數據結構

以下的代碼是一個簡單的JSON數組示例:app

  ["北京","上海","廣州"]

 

值的類型ide

  在JSON的對象和數組結構中,value值不只能夠是數字、字符串等簡單數據類型,還能夠是對象、數組等,this

JSON中值的類型spa

  所以,咱們能夠使用對象和數組的組合構成複雜的數據結構。以下的代碼使用對象結構定義了一個「students」對象,在「students」對象中包含了一個學生數組,而學生數組中的值又是JSON對象。

1     {
2         "students":
3         [
4         {"name":"jack","age":23},
5         {"name":"rose","age":24}
6         ]
7     } 

 

看一下android下原生解析json的代碼。代碼比較簡陋。

 1 package com.example.android_json;
 2 
 3 import com.example.android_json.jsonCreate.jsonCreate;
 4 import com.example.android_json.jsonCreate.jsonParse;
 5 
 6 import android.os.Bundle;
 7 import android.app.Activity;
 8 import android.widget.TextView;
 9 
10 public class MainActivity extends Activity {
11 
12     
13     public TextView json_text;
14     @Override
15     protected void onCreate(Bundle savedInstanceState) {
16         super.onCreate(savedInstanceState);
17         setContentView(R.layout.activity_main);
18         json_text = (TextView)findViewById(R.id.json);
19         jsonCreate jc= new jsonCreate();
20         jsonParse jp= new jsonParse();
21         String s=jc.create_json().toString();
22         
23         String s1=jc.create_json_1().toString();
24         
25         json_text.setText(s+'\n'+s1);
26         
27         
28         jp.json_pase_person(s);
29         jp.json_pase_person(s1);
30     }
31 
32 }
View Code
  1 package com.example.android_json.jsonCreate;
  2 
  3 import org.json.JSONArray;
  4 import org.json.JSONException;
  5 import org.json.JSONObject;
  6 import org.json.JSONStringer;
  7 /*
  8  * http://blog.csdn.net/lilu_leo/article/details/7000077
  9  */
 10 public class jsonCreate {
 11 /*
 12  * JSONObject, JSONArray來構建json文本 
 13  */
 14     public JSONObject  create_json(){
 15 // 假設如今要建立這樣一個json文本  
 16 //  {  
 17 //          "phone" : ["12345678", "87654321"], // 數組  
 18 //          "name" : "yuanzhifei89", // 字符串  
 19 //          "age" : 100, // 數值  
 20 //          "address" : { "country" : "china", "province" : "jiangsu" }, // 對象  
 21 //          "married" : false // 布爾值  
 22 //  }  
 23       
 24     try {  
 25         // 首先最外層是{},是建立一個對象  
 26         JSONObject person = new JSONObject();  
 27         // 第一個鍵phone的值是數組,因此須要建立數組對象  
 28         JSONArray phone = new JSONArray();  
 29         phone.put("12345678").put("87654321");  
 30         person.put("phone", phone);  
 31       
 32         person.put("name", "yuanzhifei89");  
 33         person.put("age", 100);  
 34         // 鍵address的值是對象,因此又要建立一個對象  
 35         JSONObject address = new JSONObject();  
 36         address.put("country", "china");  
 37         address.put("province", "jiangsu");  
 38         person.put("address", address);    
 39         person.put("married", false);  
 40         
 41         
 42         /*    
 43             getType和optType api的使用 
 44             getType能夠將要獲取的鍵的值轉換爲指定的類型,若是沒法轉換或沒有值則拋出JSONException 
 45             optType也是將要獲取的鍵的值轉換爲指定的類型,沒法轉換或沒有值時返回用戶提供或這默認提供的值 
 46         */    
 47         
 48         // 全部使用的對象都是用上面建立的對象  
 49         // 將第一個電話號碼轉換爲數值和將名字轉換爲數值  
 50 //        phone.getLong(0);  
 51 //        person.getLong("name"); // 會拋異常,由於名字沒法轉換爲long        
 52 //        phone.optLong(0); // 代碼內置的默認值  
 53 //        phone.optLong(0, 1000); // 用戶提供的默認值  
 54 //        person.optLong("name");  
 55 //        person.optLong("name", 1000); // 不像上面那樣拋異常,而是返回1000  
 56         
 57         return    person ;
 58     } catch (JSONException ex) {  
 59         // 鍵爲null或使用json不支持的數字格式(NaN, infinities)  
 60         throw new RuntimeException(ex);  
 61     }
 62 }
 63     
 64     
 65     /*
 66      * JSONStringer來構建json文本 
 67      */
 68     public JSONStringer create_json_1(){
 69         try {  
 70             JSONStringer jsonText = new JSONStringer();  
 71             // 首先是{,對象開始。object和endObject必須配對使用  
 72             jsonText.object();  
 73               
 74             jsonText.key("phone");  
 75             // 鍵phone的值是數組。array和endArray必須配對使用  
 76             jsonText.array();  
 77             jsonText.value("12345678").value("87654321");  
 78             jsonText.endArray();  
 79               
 80             jsonText.key("name");  
 81             jsonText.value("xxxxxxxx");  
 82             jsonText.key("age");  
 83             jsonText.value(100);  
 84               
 85             jsonText.key("address");  
 86             // 鍵address的值是對象  
 87             jsonText.object();  
 88             jsonText.key("country");  
 89             jsonText.value("china");  
 90             jsonText.key("province");  
 91             jsonText.value("jiangsu");  
 92             jsonText.endObject();  
 93               
 94             jsonText.key("married");  
 95             jsonText.value(false);  
 96               
 97             // },對象結束  
 98             jsonText.endObject();  
 99             return    jsonText ;
100         } catch (JSONException ex) {  
101             throw new RuntimeException(ex);  
102         }  
103     }
104     
105 }
View Code
  1 package com.example.android_json.jsonCreate;
  2 
  3 import org.json.JSONArray;
  4 import org.json.JSONException;
  5 import org.json.JSONObject;
  6 import org.json.JSONTokener;
  7 
  8 import android.widget.Adapter;
  9 
 10 import com.example.android_json.javabean.Address;
 11 import com.example.android_json.javabean.Person;
 12 
 13 public class jsonParse {
 14 
 15 private static final String[][] String = null;
 16     //  {  
 17 //  "phone" : ["12345678", "87654321"], // 數組  
 18 //  "name" : "yuanzhifei89", // 字符串  
 19 //  "age" : 100, // 數值  
 20 //  "address" : { "country" : "china", "province" : "jiangsu" }, // 對象  
 21 //  "married" : false // 布爾值  
 22 //}  
 23     public void json_pase_0(){
 24         final String JSON =   
 25                 "{" +  
 26                     "   \"phone\" : [\"12345678\", \"87654321\"]," +  
 27                     "   \"name\" : \"yuanzhifei89\"," +  
 28                     "   \"age\" : 100," +  
 29                     "   \"address\" : { \"country\" : \"china\", \"province\" : \"jiangsu\" }," +  
 30                     "   \"married\" : false," +  
 31                 "}";  
 32                   
 33                 try {  
 34                     JSONTokener jsonParser = new JSONTokener(JSON);  
 35                     // 此時還未讀取任何json文本,直接讀取就是一個JSONObject對象。  
 36                     // 若是此時的讀取位置在"name" : 了,那麼nextValue就是"yuanzhifei89"(String)  
 37                     JSONObject person = (JSONObject) jsonParser.nextValue();  
 38                     // 接下來的就是JSON對象的操做了  
 39                     person.getJSONArray("phone");  
 40                     person.getString("name");  
 41                     person.getInt("age");  
 42                     person.getJSONObject("address");  
 43                     person.getBoolean("married");  
 44                 } catch (JSONException ex) {  
 45                     // 異常處理代碼  
 46                 }  
 47                 
 48                 try {  
 49                     JSONTokener jsonParser = new JSONTokener(JSON);  
 50                     // 繼續向下讀8個json文本中的字符。此時剛開始,即在{處  
 51                     jsonParser.next(8); //{    "phone。tab算一個字符  
 52                       
 53                     // 繼續向下讀1個json文本中的字符  
 54                     jsonParser.next(); //"  
 55                       
 56                     // 繼續向下讀取一個json文本中的字符。該字符不是空白、同時也不是注視中的字符  
 57                     jsonParser.nextClean(); //:  
 58                       
 59                     // 返回當前的讀取位置到第一次遇到'a'之間的字符串(不包括a)。  
 60                     jsonParser.nextString('a'); //  ["12345678", "87654321"],    "n(前面有兩個空格)  
 61                       
 62                     // 返回當前讀取位置到第一次遇到字符串中(如"0089")任意字符之間的字符串,同時該字符是trimmed的。(此處就是第一次遇到了89)  
 63                     jsonParser.nextTo("0089"); //me" : "yuanzhifei  
 64                       
 65                     // 讀取位置撤銷一個  
 66                     jsonParser.back();  
 67                     jsonParser.next(); //i  
 68                       
 69                     // 讀取位置前進到指定字符串處(包括字符串)  
 70                     jsonParser.skipPast("address");  
 71                     jsonParser.next(8); //" : { "c  
 72                       
 73                     // 讀取位置前進到執行字符處(不包括字符)  
 74                     jsonParser.skipTo('m');  
 75                     jsonParser.next(8); //married"  
 76                 } catch (JSONException ex) {  
 77                     // 異常處理代碼  
 78                 }  
 79     }
 80     public void json_pase_person(String JSON){
 81         Person person = new Person();
 82         try {  
 83          JSONTokener jsonParser = new JSONTokener(JSON);  
 84             // 此時還未讀取任何json文本,直接讀取就是一個JSONObject對象。  
 85             // 若是此時的讀取位置在"name" : 了,那麼nextValue就是"yuanzhifei89"(String)  
 86             JSONObject person_temp = (JSONObject) jsonParser.nextValue();  
 87             // 接下來的就是JSON對象的操做了  
 88             JSONArray jsonArray =person_temp.getJSONArray("phone");  
 89             
 90             int arraylength=jsonArray.length();
 91             System.out.println(arraylength);
 92             String [] phone = new String [arraylength];
 93             for(int i=0;i<arraylength;i++){
 94                 phone[i]=jsonArray.opt(i).toString();
 95             }
 96             person.setPhone(phone);
 97             
 98             person.setName(person_temp.getString("name"));
 99             person.setAge(person_temp.getInt("age")) ; 
100             person.setMarried(person_temp.getBoolean("married"));
101          
102             person.setAddress(json_pase_address(person_temp.getJSONObject("address")));
103              
104             
105            System.out.println( person.toString());
106             
107            }
108             catch (JSONException ex) {  
109                 // 異常處理代碼  
110             }  
111     }
112     public Address json_pase_address(JSONObject JSON){
113         Address address = new Address();
114         try {  
115     
116             address.setCountry(JSON.getString("country"));
117             address.setProvince(JSON.getString("province"));
118            
119            System.out.println( address.toString());
120             
121            }
122             catch (JSONException ex) {  
123                 // 異常處理代碼  
124             }
125         return address;  
126     }
127 }
View Code

 

javabean類,通常都是把json解析賦值給一個javabean

 1 package com.example.android_json.javabean;
 2 
 3 public class Address{
 4     String country;
 5     String province;
 6     public String getCountry() {
 7         return country;
 8     }
 9     public void setCountry(String country) {
10         this.country = country;
11     }
12     public String getProvince() {
13         return province;
14     }
15     public void setProvince(String province) {
16         this.province = province;
17     }
18     @Override
19     public String toString() {
20         return "Address [country=" + country + ", province=" + province + "]";
21     }
22 }
View Code

 

 1 package com.example.android_json.javabean;
 2 
 3 import java.util.Arrays;
 4 
 5 public class Person {
 6     String name;
 7     int age;
 8     boolean married;
 9     String [] phone;
10     Address address;
11     public String getName() {
12         return name;
13     }
14     public void setName(String name) {
15         this.name = name;
16     }
17     public int getAge() {
18         return age;
19     }
20     public void setAge(int age) {
21         this.age = age;
22     }
23     public boolean isMarried() {
24         return married;
25     }
26     public void setMarried(boolean married) {
27         this.married = married;
28     }
29     public String[] getPhone() {
30         return phone;
31     }
32     public void setPhone(String[] phone) {
33         this.phone = phone;
34     }
35     public Address getAddress() {
36         return address;
37     }
38     public void setAddress(Address address) {
39         this.address = address;
40     }
41     @Override
42     public String toString() {
43         return "Person [name=" + name + ", age=" + age + ", married=" + married
44                 + ", phone=" + Arrays.toString(phone) + ", address=" + address
45                 + "]";
46     }
47     
48 }
View Code
相關文章
相關標籤/搜索