首先要导入 net.sf.json.JSONArray和net.sf.json.JSONObject 两个jar 包
String str = "[{name:'name1',value:'value1'},{name:'name2',value:'value2'},{name:'name3',value:'value3'}]" ; // 一个未转化的字符串 JSONArray json = JSONArray.fromObject(str ); // 首先把字符串转成 JSONArray 对象 if(json.size()>0){ for(int i=0;i<json.size();i++){ JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组,把每一个对象转成 json 对象 System.out.println(job.get("name")+"=") ; // 得到 每个对象中的属性值 } }
public static void test() { JSONObject jsonAlarmMsg = null; //{"code":"1","data":[{"file_name":"51信用卡","file_value":[{"index_value":4472,"index_name":"笔数"},{"index_value":9923,"index_name":"金额"}]},{"file_name":"量化派","file_value":[{"index_value":8303,"index_name":"笔数"},{"index_value":9659,"index_name":"金额"}]},{"file_name":"携程","file_value":[{"index_value":1504,"index_name":"笔数"},{"index_value":5067,"index_name":"金额"}]}],"title_type":"当日各渠道笔数-金额"} String code = jsonAlarmMsg.getString("code"); //如果 code等于1 数据正常 if ("1".equals(code)) { String title_type = jsonAlarmMsg.getString("title_type"); System.out.println(title_type); //"data":[{"file_name":"51信用卡","file_value":[{"index_value":4472,"index_name":"笔数"},{"index_value":9923,"index_name":"金额"}]},{"file_name":"量化派","file_value":[{"index_value":8303,"index_name":"笔数"},{"index_value":9659,"index_name":"金额"}]},{"file_name":"携程","file_value":[{"index_value":1504,"index_name":"笔数"},{"index_value":5067,"index_name":"金额"}]}] String data = jsonAlarmMsg.getString("data"); //解析data JSONArray jsonArray = JSONArray.fromObject(data); // 首先把字符串转成 JSONArray 对象 //如果里面有数据 if (jsonArray.size() > 0) { for (int i = 0; i < jsonArray.size(); i++) { net.sf.json.JSONObject jsonObject = jsonArray.getJSONObject(i); //{"file_name":"51信用卡","file_value":[{"index_value":4472,"index_name":"笔数"},{"index_value":9923,"index_name":"金额"}]} System.out.println(jsonObject.get("file_name")); System.out.println(jsonObject.get("file_value")); } } else { System.out.println("转换JSON,jsonArray.size()无数据"); } } else { System.out.println("code编码等于1,数据有误"); } }