Json转换利器Gson实例

Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。

jar和源码下载地址: http://code.google.com/p/google-gson/downloads/list


实体类:

[java]  view plain copy
  1.   
[java]  view plain copy
  1. public class Student {  
  2.     private int id;  
  3.     private String name;  
  4.     private Date birthDay;  
  5.   
  6.     public int getId() {  
  7.         return id;  
  8.     }  
  9.   
  10.     public void setId(int id) {  
  11.         this.id = id;  
  12.     }  
  13.   
  14.     public String getName() {  
  15.         return name;  
  16.     }  
  17.   
  18.     public void setName(String name) {  
  19.         this.name = name;  
  20.     }  
  21.   
  22.     public Date getBirthDay() {  
  23.         return birthDay;  
  24.     }  
  25.   
  26.     public void setBirthDay(Date birthDay) {  
  27.         this.birthDay = birthDay;  
  28.     }  
  29.   
  30.     @Override  
  31.     public String toString() {  
  32.         return "Student [birthDay=" + birthDay + ", id=" + id + ", name="  
  33.                 + name + "]";  
  34.     }  
  35.   
  36. }  

测试类:

[html]  view plain copy
  1. import java.util.ArrayList;  
  2. import java.util.Date;  
  3. import java.util.List;  
  4.   
  5. import com.google.gson.Gson;  
  6. import com.google.gson.reflect.TypeToken;  
  7.   
  8. public class GsonTest1 {  
  9.   
  10.     public static void main(String[] args) {  
  11.         Gson gson = new Gson();  
  12.   
  13.         Student student1 = new Student();  
  14.         student1.setId(1);  
  15.         student1.setName("李坤");  
  16.         student1.setBirthDay(new Date());  
  17.   
  18.         // //  
  19.         System.out.println("----------简单对象之间的转化-------------");  
  20.         // 简单的bean转为json  
  21.         String s1 = gson.toJson(student1);  
  22.         System.out.println("简单Bean转化为Json===" + s1);  
  23.   
  24.         // json转为简单Bean  
  25.         Student student = gson.fromJson(s1, Student.class);  
  26.         System.out.println("Json转为简单Bean===" + student);  
  27.         // 结果:  
  28.         // 简单Bean转化为Json==={"id":1,"name":"李坤","birthDay":"Jun 22, 2012 8:27:52 AM"}  
  29.         // Json转为简单Bean===Student [birthDay=Fri Jun 22 08:27:52 CST 2012, id=1,  
  30.         // name=李坤]  
  31.         // //  
  32.   
  33.         Student student2 = new Student();  
  34.         student2.setId(2);  
  35.         student2.setName("曹贵生");  
  36.         student2.setBirthDay(new Date());  
  37.   
  38.         Student student3 = new Student();  
  39.         student3.setId(3);  
  40.         student3.setName("柳波");  
  41.         student3.setBirthDay(new Date());  
  42.   
  43.         List<Student> list = new ArrayList<Student>();  
  44.         list.add(student1);  
  45.         list.add(student2);  
  46.         list.add(student3);  
  47.   
  48.         System.out.println("----------带泛型的List之间的转化-------------");  
  49.         // 带泛型的list转化为json  
  50.         String s2 = gson.toJson(list);  
  51.         System.out.println("带泛型的list转化为json==" + s2);  
  52.   
  53.         // json转为带泛型的list  
  54.         List<Student> retList = gson.fromJson(s2,  
  55.                 new TypeToken<List<Student>>() {  
  56.                 }.getType());  
  57.         for (Student stu : retList) {  
  58.             System.out.println(stu);  
  59.         }  
  60.   
  61.         // 结果:  
  62.         // 带泛型的list转化为json==[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 8:28:52 AM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 8:28:52 AM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 8:28:52 AM"}]  
  63.         // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=1name=李坤]  
  64.         // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=2name=曹贵生]  
  65.         // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=3name=柳波]  
  66.   
  67.     }  
  68. }  

执行结果:

[plain]  view plain copy
  1. ----------简单对象之间的转化-------------  
  2. 简单Bean转化为Json==={"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:10:31 PM"}  
  3. Json转为简单Bean===Student [birthDay=Fri Jun 22 21:10:31 CST 2012, id=1, name=李坤]  
  4. ----------带泛型的List之间的转化-------------  
  5. 带泛型的list转化为json==[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:10:31 PM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 9:10:31 PM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 9:10:31 PM"}]  
  6. Student [birthDay=Fri Jun 22 21:10:31 CST 2012, id=1, name=李坤]  
  7. Student [birthDay=Fri Jun 22 21:10:31 CST 2012, id=2, name=曹贵生]  
  8. Student [birthDay=Fri Jun 22 21:10:31 CST 2012, id=3, name=柳波]  

Json转换利器Gson之实例一-简单对象转化和带泛型的List转化 (http://blog.csdn.net/lk_blog/article/details/7685169)
Json转换利器Gson之实例二-Gson注解和GsonBuilder (http://blog.csdn.net/lk_blog/article/details/7685190)
Json转换利器Gson之实例三-Map处理(上) (http://blog.csdn.net/lk_blog/article/details/7685210)
Json转换利器Gson之实例四-Map处理(下) (http://blog.csdn.net/lk_blog/article/details/7685224)
Json转换利器Gson之实例五-实际开发中的特殊需求处理 (http://blog.csdn.net/lk_blog/article/details/7685237)
Json转换利器Gson之实例六-注册TypeAdapter及处理Enum类型 (http://blog.csdn.net/lk_blog/article/details/7685347)


实例代码下载: http://download.csdn.net/detail/lk_blog/4387822


Android中的JSON

1、JSON(JavaScript Object Notation) 定义:
一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性。业内主流技术为其提供了完整的解决方案(有点类似于正则表达式,获得了当今大部分语言的支持),从而可以在不同平台间进行数据交换。JSON采用兼容性很高的文本格式,同时也具备类似于C语言体系的行为。 – Json.org

 

2、JSON的结构:
(1) Name/Value Pairs(无序的):类似所熟知的Keyed list、 Hash table、Disctionary和Associative array。
      在Android平台中同时存在另外一个类 "Bundle",某种程度上具有相似的行为。
(2) Array(有序的):一组有序的数据列表。

 

对象
对象是一个无序的Name/Value Pairs集合。{ name:value , name:value , name:value ....  }

例子:{ "name":"小猪","age":20 }

 

Array
      Array是值(value)的有序集合。[ value , value , value ...... ] 
      值(value)可以是双引号括起来的字符串(string)、数值(number)、true、false、 null、对象(object)或者数组(array)。这些结构可以嵌套。
      字符串(string)是由双引号包围的任意数量Unicode字符的集合,使用反斜线转义。一个字符(character)即一个单独的字符串(character string)。 例如:/ + " / / b f n r t u 进行转义。

 

 

例子1: Array里面包含对象(object)
[ {"id":1,"name":"小猪" ,"age”:22} , {"id":2,"name":"小猫","age”:23} ,  .......]

 

例子2:同样对象(object)中可以包含Array
(1)一个对象包含1个数组,2个子对象
{"root":[{"id":"001","name":"小猪"},{"id":"002","name":"小猫"},{"id":"003","name":"小狗"}],
 "total":3,
 "success":true
}

 

(2)也可以对象嵌套子对象,子对象再嵌套数组
{"calendar": 
    {"calendarlist": 
            [ 
            {"id":"001","name":"小猪"}, 
            {"id":"002","name":"小猫"} 
            ] 
    } 
}

总之,格式多种多样,可以互相嵌套

 

==================================================================================


在Android中包含四个与JSON相关的类和一个Exceptions:
JSONArray

JSONObject

JSONStringer

JSONTokener

JSONException

 

(1)JSONObject:
      这是系统中有关JSON定义的基本单元,其包含一对儿(Key/Value)数值。

      它对外部(External:应用toString()方法输出的数值)调用的响应体现为一个标准的字符串(例如:{“JSON”: “Hello, World”},最外被大括号包裹,其中的Key和Value被冒号”:”分隔)。其对于内部(Internal)行为的操作格式略微,例如:初始化一个JSONObject实例,引用内部的put()方法添加数值:new JSONObject().put(“JSON”, “Hello, World!”),在Key和Value之间是以逗号”,”分隔。

      Value的类型包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。

有两个不同的取值方法:

      get(): 在确定数值存在的条件下使用,否则当无法检索到相关Key时,将会抛出一个Exception信息。

      opt(): 这个方法相对比较灵活,当无法获取所指定数值时,将会返回一个默认数值,并不会抛出异常。

 

 

(2)JSONArray:
      它代表一组有序的数值。将其转换为String输出(toString)所表现的形式是用方括号包裹,数值以逗号”,”分隔(例如:[value1,value2,value3],大家可以亲自利用简短的代码更加直观的了解其格式)。这个类的内部同样具有查询行为,get()和opt()两种方法都可以通过index索引返回指定的数值,put()方法用来添加或者替换数值。

      同样这个类的value类型可以包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。

 

(3)JSONStringer:
      根据官方的解释,这个类可以帮助快速和便捷的创建JSONtext。其最大的优点在于可以减少由于格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntaxrules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。

      根据下边的实例来了解其它相关信息:

 

  1. String myString = new JSONStringer().object()   
  2. .key("name")  
  3. .value("小猪")   
  4. .endObject()  
  5. .toString();  
[java]  view plain copy
  1. String myString = new JSONStringer().object()   
  2. .key("name")  
  3. .value("小猪")   
  4. .endObject()  
  5. .toString();  

结果是一组标准格式的JSON text:{"name" : "小猪"}

其中的.object()和.endObject()必须同时使用,是为了按照Object标准给数值添加边界。同样,针对数组也有一组标准的方法来生成边界.array()和.endArray()。

 

 

(4)JSONTokener:
      这个是系统为JSONObject和JSONArray构造器解析JSON source string的类,它可以从source string中提取数值信息。

JSONException:是JSON.org类抛出的异常信息。

下面引用一个完整的应用实例:

应用JSONObject存储Map类型数值:


  1. public static JSONObject getJSON(Map map) {     
  2.     Iterator iter = map.entrySet().iterator();     
  3.     JSONObject holder = new JSONObject();     
  4.     while (iter.hasNext()) {     
  5.         Map.Entry pairs = (Map.Entry) iter.next();     
  6.         String key = (String) pairs.getKey();     
  7.         Map m = (Map) pairs.getValue();     
  8.         JSONObject data = new JSONObject();     
  9.         try {     
  10.             Iterator iter2 = m.entrySet().iterator();     
  11.             while (iter2.hasNext()) {     
  12.                 Map.Entry pairs2 = (Map.Entry) iter2.next();     
  13.                 data.put((String) pairs2.getKey(), (String) pairs2     
  14.                         .getValue());     
  15.             }     
  16.             holder.put(key, data);     
  17.         } catch (JSONException e) {     
  18.             Log.e("Transforming""There was an error packaging JSON", e);     
  19.         }     
  20.     }     
  21.     return holder;     
  22. }    
[java]  view plain copy
  1. public static JSONObject getJSON(Map map) {     
  2.     Iterator iter = map.entrySet().iterator();     
  3.     JSONObject holder = new JSONObject();     
  4.     while (iter.hasNext()) {     
  5.         Map.Entry pairs = (Map.Entry) iter.next();     
  6.         String key = (String) pairs.getKey();     
  7.         Map m = (Map) pairs.getValue();     
  8.         JSONObject data = new JSONObject();     
  9.         try {     
  10.             Iterator iter2 = m.entrySet().iterator();     
  11.             while (iter2.hasNext()) {     
  12.                 Map.Entry pairs2 = (Map.Entry) iter2.next();     
  13.                 data.put((String) pairs2.getKey(), (String) pairs2     
  14.                         .getValue());     
  15.             }     
  16.             holder.put(key, data);     
  17.         } catch (JSONException e) {     
  18.             Log.e("Transforming""There was an error packaging JSON", e);     
  19.         }     
  20.     }     
  21.     return holder;     
  22. }    

 

下面是详细的例子:


  1. import java.io.ByteArrayOutputStream;     
  2. import java.io.InputStream;     
  3. import java.net.*;     
  4. import java.util.ArrayList;     
  5. import java.util.HashMap;     
  6. import java.util.List;     
  7. import java.util.Map;     
  8. import org.json.JSONArray;     
  9. import org.json.JSONObject;     
  10. import android.util.Log;     
  11.     
  12. public class JSON {     
  13.     
  14.          
  15.     /**   
  16.      * 获取"数组形式"的JSON数据,   
  17.       * 数据形式:[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]   
  18.      * @param path  网页路径   
  19.       * @return  返回List   
  20.      * @throws Exception   
  21.      */    
  22.     public static List<Map<String, String>> getJSONArray(String path) throws Exception {     
  23.         String json = null;     
  24.         List<Map<String, String>> list = new ArrayList<Map<String, String>>();     
  25.         Map<String, String> map = null;     
  26.         URL url = new URL(path);     
  27.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.     
  28.         conn.setConnectTimeout(5 * 1000);   // 单位是毫秒,设置超时时间为5秒     
  29.         conn.setRequestMethod("GET");       // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET     
  30.         if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败     
  31.             InputStream is = conn.getInputStream(); // 获取输入流     
  32.             byte[] data = readStream(is);   // 把输入流转换成字符数组     
  33.             json = new String(data);        // 把字符数组转换成字符串     
  34.                  
  35.             //数据形式:[{"id":1,"name":"小猪","age":22},{"id":2,"name":"小猫","age":23}]     
  36.             JSONArray jsonArray = new JSONArray(json); //数据直接为一个数组形式,所以可以直接 用android提供的框架JSONArray读取JSON数据,转换成Array     
  37.     
  38.             for (int i = 0; i < jsonArray.length(); i++) {     
  39.                 JSONObject item = jsonArray.getJSONObject(i); //每条记录又由几个Object对象组成     
  40.                 int id = item.getInt("id");     // 获取对象对应的值     
  41.                 String name = item.getString("name");     
  42.     
  43.                 map = new HashMap<String, String>(); // 存放到MAP里面     
  44.                 map.put("id", id + "");     
  45.                 map.put("name", name);     
  46.                 list.add(map);     
  47.             }     
  48.         }     
  49.     
  50.         // ***********测试数据******************     
  51.         for (Map<String, String> list2 : list) {     
  52.             String id = list2.get("id");     
  53.             String name = list2.get("name");     
  54.             Log.i("abc""id:" + id + " | name:" + name);     
  55.         }     
  56.     
  57.         return list;     
  58.     }     
  59.     
  60.     /**   
  61.      * 获取"对象形式"的JSON数据,   
  62.      * 数据形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]}   
  63.      * @param path  网页路径   
  64.      * @return  返回List   
  65.      * @throws Exception   
  66.      */    
  67.     public static List<Map<String, String>> getJSONObject(String path) throws Exception {     
  68.         List<Map<String, String>> list = new ArrayList<Map<String, String>>();     
  69.         Map<String, String> map = null;     
  70.         URL url = new URL(path);     
  71.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.     
  72.         conn.setConnectTimeout(5 * 1000);   // 单位是毫秒,设置超时时间为5秒     
  73.         conn.setRequestMethod("GET");       // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET     
  74.         if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败     
  75.             InputStream is = conn.getInputStream(); // 获取输入流     
  76.             byte[] data = readStream(is);   // 把输入流转换成字符数组     
  77.             String json = new String(data); // 把字符数组转换成字符串     
  78.                  
  79.                  
  80.             //数据形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]}     
  81.             JSONObject jsonObject=new JSONObject(json);     //返回的数据形式是一个Object类型,所以可以直接转换成一个Object     
  82.             int total=jsonObject.getInt("total");     
  83.             Boolean success=jsonObject.getBoolean("success");     
  84.             Log.i("abc""total:" + total + " | success:" + success);   //测试数据     
  85.                  
  86.             JSONArray jsonArray = jsonObject.getJSONArray("arrayData");//里面有一个数组数据,可以用getJSONArray获取数组     
  87.             for (int i = 0; i < jsonArray.length(); i++) {     
  88.                 JSONObject item = jsonArray.getJSONObject(i); // 得到每个对象     
  89.                 int id = item.getInt("id");     // 获取对象对应的值     
  90.                 String name = item.getString("name");     
  91.     
  92.                 map = new HashMap<String, String>(); // 存放到MAP里面     
  93.                 map.put("id", id + "");     
  94.                 map.put("name", name);     
  95.                 list.add(map);     
  96.             }     
  97.         }     
  98.     
  99.         // ***********测试数据******************     
  100.              
  101.         for (Map<String, String> list2 : list) {     
  102.             String id = list2.get("id");     
  103.             String name = list2.get("name");     
  104.             Log.i("abc""id:" + id + " | name:" + name);     
  105.         }     
  106.     
  107.         return list;     
  108.     }     
  109.          
  110.          
  111.     /**   
  112.      * 获取类型复杂的JSON数据   
  113.      *数据形式:   
  114.         {"name":"小猪",   
  115.          "age":23,   
  116.          "content":{"questionsTotal":2,   
  117.                     "questions": [ { "question": "what's your name?", "answer": "小猪"},{"question": "what's your age", "answer": "23"}]   
  118.                    }   
  119.         }   
  120.      * @param path  网页路径   
  121.      * @return  返回List   
  122.      * @throws Exception   
  123.      */    
  124.     public static List<Map<String, String>> getJSON(String path) throws Exception {     
  125.         List<Map<String, String>> list = new ArrayList<Map<String, String>>();     
  126.         Map<String, String> map = null;     
  127.         URL url = new URL(path);     
  128.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.     
  129.         conn.setConnectTimeout(5 * 1000);   // 单位是毫秒,设置超时时间为5秒     
  130.         conn.setRequestMethod("GET");       // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET     
  131.         if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败     
  132.             InputStream is = conn.getInputStream(); // 获取输入流     
  133.             byte[] data = readStream(is);   // 把输入流转换成字符数组     
  134.             String json = new String(data); // 把字符数组转换成字符串     
  135.                  
  136.                  
  137.             /*数据形式:   
  138.                 {"name":"小猪",   
  139.                  "age":23,   
  140.                  "content":{"questionsTotal":2,   
  141.                             "questions": [ { "question": "what's your name?", "answer": "小猪"},{"question": "what's your age", "answer": "23"}]   
  142.                            }   
  143.                 }   
  144.             */       
  145.             JSONObject jsonObject=new JSONObject(json);     //返回的数据形式是一个Object类型,所以可以直接转换成一个Object     
  146.             String name=jsonObject.getString("name");            
  147.             int age=jsonObject.getInt("age");     
  148.             Log.i("abc""name:" + name + " | age:" + age); //测试数据     
  149.                  
  150.             JSONObject contentObject=jsonObject.getJSONObject("content");       //获取对象中的对象     
  151.             String questionsTotal=contentObject.getString("questionsTotal");    //获取对象中的一个值     
  152.             Log.i("abc""questionsTotal:" + questionsTotal);   //测试数据     
  153.                  
  154.             JSONArray contentArray=contentObject.getJSONArray("questions");     //获取对象中的数组     
  155.             for (int i = 0; i < contentArray.length(); i++) {     
  156.                 JSONObject item = contentArray.getJSONObject(i); // 得到每个对象     
  157.                 String question = item.getString("question");   // 获取对象对应的值     
  158.                 String answer = item.getString("answer");     
  159.     
  160.                 map = new HashMap<String, String>(); // 存放到MAP里面     
  161.                 map.put("question", question);     
  162.                 map.put("answer", answer);     
  163.                 list.add(map);     
  164.             }     
  165.         }     
  166.     
  167.         // ***********测试数据******************     
  168.              
  169.         for (Map<String, String> list2 : list) {     
  170.             String question = list2.get("question");     
  171.             String answer = list2.get("answer");     
  172.             Log.i("abc""question:" + question + " | answer:" + answer);     
  173.         }     
  174.     
  175.         return list;     
  176.     }     
  177.          
  178.          
  179.          
  180.          
  181.     /**   
  182.      * 把输入流转换成字符数组   
  183.      * @param inputStream   输入流   
  184.      * @return  字符数组   
  185.      * @throws Exception   
  186.      */    
  187.     public static byte[] readStream(InputStream inputStream) throws Exception {     
  188.         ByteArrayOutputStream bout = new ByteArrayOutputStream();     
  189.         byte[] buffer = new byte[1024];     
  190.         int len = 0;     
  191.         while ((len = inputStream.read(buffer)) != -1) {     
  192.             bout.write(buffer, 0, len);     
  193.         }     
  194.         bout.close();     
  195.         inputStream.close();     
  196.     
  197.         return bout.toByteArray();     
  198.     }     
  199.     
  200. }    
[java]  view plain copy
  1. import java.io.ByteArrayOutputStream;     
  2. import java.io.InputStream;     
  3. import java.net.*;     
  4. import java.util.ArrayList;     
  5. import java.util.HashMap;     
  6. import java.util.List;     
  7. import java.util.Map;     
  8. import org.json.JSONArray;     
  9. import org.json.JSONObject;     
  10. import android.util.Log;     
  11.     
  12. public class JSON {     
  13.     
  14.          
  15.     /**   
  16.      * 获取"数组形式"的JSON数据,   
  17.       * 数据形式:[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]   
  18.      * @param path  网页路径   
  19.       * @return  返回List   
  20.      * @throws Exception   
  21.      */    
  22.     public static List<Map<String, String>> getJSONArray(String path) throws Exception {     
  23.         String json = null;     
  24.         List<Map<String, String>> list = new ArrayList<Map<String, String>>();     
  25.         Map<String, String> map = null;     
  26.         URL url = new URL(path);     
  27.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.     
  28.         conn.setConnectTimeout(5 * 1000);   // 单位是毫秒,设置超时时间为5秒     
  29.         conn.setRequestMethod("GET");       // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET     
  30.         if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败     
  31.             InputStream is = conn.getInputStream(); // 获取输入流     
  32.             byte[] data = readStream(is);   // 把输入流转换成字符数组     
  33.             json = new String(data);        // 把字符数组转换成字符串     
  34.                  
  35.             //数据形式:[{"id":1,"name":"小猪","age":22},{"id":2,"name":"小猫","age":23}]     
  36.             JSONArray jsonArray = new JSONArray(json); //数据直接为一个数组形式,所以可以直接 用android提供的框架JSONArray读取JSON数据,转换成Array     
  37.     
  38.             for (int i = 0; i < jsonArray.length(); i++) {     
  39.                 JSONObject item = jsonArray.getJSONObject(i); //每条记录又由几个Object对象组成     
  40.                 int id = item.getInt("id");     // 获取对象对应的值     
  41.                 String name = item.getString("name");     
  42.     
  43.                 map = new HashMap<String, String>(); // 存放到MAP里面     
  44.                 map.put("id", id + "");     
  45.                 map.put("name", name);     
  46.                 list.add(map);     
  47.             }     
  48.         }     
  49.     
  50.         // ***********测试数据******************     
  51.         for (Map<String, String> list2 : list) {     
  52.             String id = list2.get("id");     
  53.             String name = list2.get("name");     
  54.             Log.i("abc""id:" + id + " | name:" + name);     
  55.         }     
  56.     
  57.         return list;     
  58.     }     
  59.     
  60.     /**   
  61.      * 获取"对象形式"的JSON数据,   
  62.      * 数据形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]}   
  63.      * @param path  网页路径   
  64.      * @return  返回List   
  65.      * @throws Exception   
  66.      */    
  67.     public static List<Map<String, String>> getJSONObject(String path) throws Exception {     
  68.         List<Map<String, String>> list = new ArrayList<Map<String, String>>();     
  69.         Map<String, String> map = null;     
  70.         URL url = new URL(path);     
  71.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.     
  72.         conn.setConnectTimeout(5 * 1000);   // 单位是毫秒,设置超时时间为5秒     
  73.         conn.setRequestMethod("GET");       // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET     
  74.         if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败     
  75.             InputStream is = conn.getInputStream(); // 获取输入流     
  76.             byte[] data = readStream(is);   // 把输入流转换成字符数组     
  77.             String json = new String(data); // 把字符数组转换成字符串     
  78.                  
  79.                  
  80.             //数据形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小猪"},{"id":2,"name":"小猫"}]}     
  81.             JSONObject jsonObject=new JSONObject(json);     //返回的数据形式是一个Object类型,所以可以直接转换成一个Object     
  82.             int total=jsonObject.getInt("total");     
  83.             Boolean success=jsonObject.getBoolean("success");     
  84.             Log.i("abc""total:" + total + " | success:" + success);   //测试数据     
  85.                  
  86.             JSONArray jsonArray = jsonObject.getJSONArray("arrayData");//里面有一个数组数据,可以用getJSONArray获取数组     
  87.             for (int i = 0; i < jsonArray.length(); i++) {     
  88.                 JSONObject item = jsonArray.getJSONObject(i); // 得到每个对象     
  89.                 int id = item.getInt("id");     // 获取对象对应的值     
  90.                 String name = item.getString("name");     
  91.     
  92.                 map = new HashMap<String, String>(); // 存放到MAP里面     
  93.                 map.put("id", id + "");     
  94.                 map.put("name", name);     
  95.                 list.add(map);     
  96.             }     
  97.         }     
  98.     
  99.         // ***********测试数据******************     
  100.              
  101.         for (Map<String, String> list2 : list) {     
  102.             String id = list2.get("id");     
  103.             String name = list2.get("name");     
  104.             Log.i("abc""id:" + id + " | name:" + name);     
  105.         }     
  106.     
  107.         return list;     
  108.     }     
  109.          
  110.          
  111.     /**   
  112.      * 获取类型复杂的JSON数据   
  113.      *数据形式:   
  114.         {"name":"小猪",   
  115.          "age":23,   
  116.          "content":{"questionsTotal":2,   
  117.                     "questions": [ { "question": "what's your name?", "answer": "小猪"},{"question": "what's your age", "answer": "23"}]   
  118.                    }   
  119.         }   
  120.      * @param path  网页路径   
  121.      * @return  返回List   
  122.      * @throws Exception   
  123.      */    
  124.     public static List<Map<String, String>> getJSON(String path) throws Exception {     
  125.         List<Map<String, String>> list = new ArrayList<Map<String, String>>();     
  126.         Map<String, String> map = null;     
  127.         URL url = new URL(path);     
  128.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.     
  129.         conn.setConnectTimeout(5 * 1000);   // 单位是毫秒,设置超时时间为5秒     
  130.         conn.setRequestMethod("GET");       // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET     
  131.         if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败     
  132.             InputStream is = conn.getInputStream(); // 获取输入流     
  133.             byte[] data = readStream(is);   // 把输入流转换成字符数组     
  134.             String json = new String(data); // 把字符数组转换成字符串     
  135.                  
  136.                  
  137.             /*数据形式:   
  138.                 {"name":"小猪",   
  139.                  "age":23,   
  140.                  "content":{"questionsTotal":2,   
  141.                             "questions": [ { "question": "what's your name?", "answer": "小猪"},{"question": "what's your age", "answer": "23"}]   
  142.                            }   
  143.                 }   
  144.             */       
  145.             JSONObject jsonObject=new JSONObject(json);     //返回的数据形式是一个Object类型,所以可以直接转换成一个Object     
  146.             String name=jsonObject.getString("name");            
  147.             int age=jsonObject.getInt("age");     
  148.             Log.i("abc""name:" + name + " | age:" + age); //测试数据     
  149.                  
  150.             JSONObject contentObject=jsonObject.getJSONObject("content");       //获取对象中的对象     
  151.             String questionsTotal=contentObject.getString("questionsTotal");    //获取对象中的一个值     
  152.             Log.i("abc""questionsTotal:" + questionsTotal);   //测试数据     
  153.                  
  154.             JSONArray contentArray=contentObject.getJSONArray("questions");     //获取对象中的数组     
  155.             for (int i = 0; i < contentArray.length(); i++) {     
  156.                 JSONObject item = contentArray.getJSONObject(i); // 得到每个对象     
  157.                 String question = item.getString("question");   // 获取对象对应的值     
  158.                 String answer = item.getString("answer");     
  159.     
  160.                 map = new HashMap<String, String>(); // 存放到MAP里面     
  161.                 map.put("question", question);     
  162.                 map.put("answer", answer);     
  163.                 list.add(map);     
  164.             }     
  165.         }     
  166.     
  167.         // ***********测试数据******************     
  168.              
  169.         for (Map<String, String> list2 : list) {     
  170.             String question = list2.get("question");     
  171.             String answer = list2.get("answer");     
  172.             Log.i("abc""question:" + question + " | answer:" + answer);     
  173.         }     
  174.     
  175.         return list;     
  176.     }     
  177.          
  178.          
  179.          
  180.          
  181.     /**   
  182.      * 把输入流转换成字符数组   
  183.      * @param inputStream   输入流   
  184.      * @return  字符数组   
  185.      * @throws Exception   
  186.      */    
  187.     public static byte[] readStream(InputStream inputStream) throws Exception {     
  188.         ByteArrayOutputStream bout = new ByteArrayOutputStream();     
  189.         byte[] buffer = new byte[1024];     
  190.         int len = 0;     
  191.         while ((len = inputStream.read(buffer)) != -1) {     
  192.             bout.write(buffer, 0, len);     
  193.         }     
  194.         bout.close();     
  195.         inputStream.close();     
  196.     
  197.         return bout.toByteArray();     
  198.     }     
  199.     
  200. }    

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值