1. 程式人生 > >關於取出JSONArray裡面的值為空並修改的程式碼

關於取出JSONArray裡面的值為空並修改的程式碼

專案中有這麼個需求,點選標題進入新聞詳細介面。很簡單的功能但是在我這個Struts2裡面確實有點費勁。首先第一步跳轉介面,然後通過載入頁面方法把資訊顯示在頁面上。

第一個遇到的問題是,跳轉介面的時候如何獲得id的值,於是在網上找到了從URL裡面獲取ID的值的程式碼:

var id="";
	$(function(){
		 var url = location.search; //獲取url中"?"符後的字串   
		  var theRequest = new Object();   
		   if (url.indexOf("?") != -1) {   
		      var str = url.substr(1);   
		      strs = str.split("&");   
		      for(var i = 0; i < strs.length; i ++) {   
		         theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);   
		      }   
		   }   
		   id=theRequest.id;
		   return theRequest; 
	})

然後接下來就比較簡單了,ajax非同步獲取物件資訊,但是問題就出現在這裡了,因為在資料庫裡面有的欄位為NULL所以,當JSONArray轉換成JSONObject的時候會報錯。報錯內容為:
Method public Java.lang.String org.apache.commons.lang.exception.NestableRuntimeException.getMessage(int) threw an exception when invoked on net.sf.json.JSONException: Object is null
The problematic instruction:
----------
==> ${msg[0]} [on line 68, column 29 in org/apache/struts2/dispatcher/error.ftl]
於是在網上找了很多種方法,沒有一個是從JSONArray中判斷為空然後修改值的方法,於是自己寫了一個。希望能幫到大家:
for (int i = 0; i < array.size(); i++) {
			JSONObject json=new JSONObject();
			json=array.getJSONObject(i);
			if(json.get("imagePath")==null||!"".equals(json.get("imagePath"))){//因為在新增的時候只有這個值可能為NULL所以我就判斷了這個。
				json.put("imagePath", " ");
			}
		}