java 字符串轉成 json 數組並且遍歷


首先要導入 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,數據有誤");
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM