JSON JSONArray 创建JSON 和 解析JSON

创建JSON   

// 假设现在要创建这样一个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

public class JSONutil {

	/**
	 * 获取"数组形式"的JSON数据,
	 * 数据形式:[{"id":1,"name":"张三","age":22},{"id":2,"name":"李四","age":23}]
	 * @param path
	 *            网页路径
	 * @return 返回List
	 * @throws Exception
	 */
	public static List<Map<String, String>> getJSONArray(String path)
			throws Exception {

		String json = null;
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Map<String, String> 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<String, String>();
				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<Map<String, String>> getJSONObject(String path)
			throws Exception {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Map<String, String> 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<String, String>(); // 存放到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<Map<String, String>> getJSON(String path)
			throws Exception {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Map<String, String> 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<String, String>(); // 存放到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<jsonArray.length();i++){
                                   JSONObject jsonItem = jsonArray.getJSONObject(i);
                                   // 对jsonItem 操作    }
                 3.  对JSONObject操作,getInt getString  getBoolean get各种类型(key)
                            int id = jsonItem.getInt("id");
                String name = jsonItem.getString("name");
                           





          

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值