JSON JSONArray 创建JSON 和 解析JSON
创建JSON
[java] view plain copy print ?- // 假设现在要创建这样一个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文本
// {
// "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 ?- public class JSONutil {
- /**
- * 获取”数组形式”的JSON数据,
- * 数据形式:[{“id”:1,”name”:”张三”,”age”:22},{“id”:2,”name”:”李四”,”age”:23}]
- * @param path
- * 网页路径
- * @return 返回List
- * @throws Exception
- */
- public static List
- throws Exception {
- String json = null;
- List
- Map
map = null; - URL url = new URL(path);
- HttpURLConnection con = (HttpURLConnection) url.openConnection();
- con.setConnectTimeout(5 * 1000);// 单位是毫秒,设置超时时间为5秒
- // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET
- con.setRequestMethod(”GET”);
- // 判断请求码是否是200码,否则失败
- if (con.getResponseCode() == 200) {
- InputStream input = con.getInputStream();// 获取输入流
- byte[] data = readStream(input);// 把输入流转换为字符数组
- json = new String(data); // 把字符数组转换成字符串
- // 数据直接为一个数组形式,所以可以直接 用android提供的框架JSONArray读取JSON数据,转换成Array
- JSONArray 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路径的,所以需要设置请求方式,可以不设置,因为默认为GET
- con.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路径的,所以需要设置请求方式,可以不设置,因为默认为GET
- con.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();
- }
- }
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
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
