JSON JSONArray 创建JSON 和 解析JSON

创建JSON   

[java] view plain copy print ?
  1. // 假设现在要创建这样一个json文本    
  2. //  {    
  3. //      “phone” : [“12345678”, “87654321”], // 数组    
  4. //      “name” : “yuanzhifei89”, // 字符串    
  5. //      “age” : 100, // 数值    
  6. //      “address” : { “country” : “china”, “province” : “jiangsu” }, // 对象    
  7. //      “married” : false // 布尔值    
  8. //  }    
  9.     
  10. try {    
  11.     // 首先最外层是{},是创建一个对象    
  12.     JSONObject person = new JSONObject();    
  13.     // 第一个键phone的值是数组,所以需要创建数组对象    
  14.     JSONArray phone = new JSONArray();    
  15.     phone.put(”12345678”).put(“87654321”);    
  16.     person.put(”phone”, phone);    
  17.     
  18.     person.put(”name”“yuanzhifei89”);    
  19.     person.put(”age”100);    
  20.     // 键address的值是对象,所以又要创建一个对象    
  21.     JSONObject address = new JSONObject();    
  22.     address.put(”country”“china”);    
  23.     address.put(”province”“jiangsu”);    
  24.     person.put(”address”, address);      
  25.     person.put(”married”false);    
  26. catch (JSONException ex) {    
  27.     // 键为null或使用json不支持的数字格式(NaN, infinities)    
  28.     throw new RuntimeException(ex);    
  29. }    
// 假设现在要创建这样一个json文本  
//  {  
//      "phone" : ["12345678", "87654321"], // 数组  
//      "name" : "yuanzhifei89", // 字符串  
//      "age" : 100, // 数值  
//      "address" : { "country" : "china", "province" : "jiangsu" }, // 对象  
//      "married" : false // 布尔值  
//  }  try {  // 首先最外层是{},是创建一个对象  JSONObject person = new JSONObject();  // 第一个键phone的值是数组,所以需要创建数组对象  JSONArray phone = new JSONArray();  phone.put("12345678").put("87654321");  person.put("phone", phone);  person.put("name", "yuanzhifei89");  person.put("age", 100);  // 键address的值是对象,所以又要创建一个对象  JSONObject address = new JSONObject();  address.put("country", "china");  address.put("province", "jiangsu");  person.put("address", address);    person.put("married", false);  
} catch (JSONException ex) {  // 键为null或使用json不支持的数字格式(NaN, infinities)  throw new RuntimeException(ex);  
}  

解析JSON

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

  主要用到: 1.String转化为JSON格式   1.1   [ { “id”:1, “name”:张三 } , { “id”:2, “name”:李四 }…]数据为数组格式 , 直接JSONArray jsonArray=new JSONArray(jsonStr); 1.2   { “total”:2 , “stateCode”:101 , “data”:[ { “id”:1, “name”:张三 } , { “id”:2, “name”:李四 } ] }  用JSONObject jsonObj = new JSONObject(jsonStr); 2.  取数组JSONArray 用for 循环 , 再用 (JSONArray) jsonArray.getJSONObject(i) for(int i=0; i JSONObject jsonItem = jsonArray.getJSONObject(i); // 对jsonItem 操作    } 3.  对JSONObject操作,getInt getString  getBoolean get各种类型(key) int id = jsonItem.getInt(“id”); String name = jsonItem.getString(“name”);




          


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部