专业的编程技术博客社区

网站首页 > 博客文章 正文

关于取出JSONArray里面的值为空并修改的代码

baijin 2024-09-18 12:06:11 博客文章 3 ℃ 0 评论

项目中有这么个需求,点击标题进入新闻详细界面。很简单的功能但是在我这个Struts2里面确实有点费劲。首先第一步跳转界面,然后通过加载页面方法把信息显示在页面上。

第一个遇到的问题是,跳转界面的时候如何获得id的值,于是在网上找到了从URL里面获取ID的值的代码:


  1. var id="";
  2. $(function(){
  3. var url = location.search; //获取url中"?"符后的字串
  4. var theRequest = new Object();
  5. if (url.indexOf("?") != -1) {
  6. var str = url.substr(1);
  7. strs = str.split("&");
  8. for(var i = 0; i < strs.length; i ++) {
  9. theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
  10. }
  11. }
  12. id=theRequest.id;
  13. return theRequest;
  14. })
  1. 然后接下来就比较简单了,ajax异步获取对象信息,但是问题就出现在这里了,因为在数据库里面有的字段为NULL所以,当JSONArray转换成JSONObject的时候会报错。报错内容为:
  2. 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
  3. The problematic instruction:
  4. ----------
  5. ==> ${msg[0]} [on line 68, column 29 in org/apache/struts2/dispatcher/error.ftl]
  6. 于是在网上找了很多种方法,没有一个是从JSONArray中判断为空然后修改值的方法,于是自己写了一个。希望能帮到大家:
  7. for (int i = 0; i < array.size(); i++) {
  8. JSONObject json=new JSONObject();
  9. json=array.getJSONObject(i);
  10. if(json.get("imagePath")==null||!"".equals(json.get("imagePath"))){//因为在添加的时候只有这个值可能为NULL所以我就判断了这个。
  11. json.put("imagePath", " ");
  12. }
  13. }

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表