android json数据解析

  • json数据结构

json中有两种数据结构:对象和数组。

 

对象

  在JSON中,一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号),冒号后是该名称的值,多个“名称:值”之间使用 “,”(逗号)分隔开来。名称需要使用双引号括起来,值如果是字符串则必须用双引号括起来,如果是数值型则不需要。

 

如下的代码是一个简单的JSON对象示例:

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

 

数组

  在JSON中,数组是值(value)的有序集合。一个数组以“[”(左中括号)开始,“]”(右中括号)结束。值之间使用 “,”(逗号)分隔开来。

如下的代码是一个简单的JSON数组示例:

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

 

值的类型

  在JSON的对象和数组结构中,value值不仅可以是数字、字符串等简单数据类型,还可以是对象、数组等,

JSON中值的类型

  因此,我们可以使用对象和数组的组合构成复杂的数据结构。如下的代码使用对象结构定义了一个“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

 

 

 

 

posted @ 2014-03-26 23:15  aosting  阅读(341)  评论(0编辑  收藏  举报