当前位置: 代码迷 >> JavaScript >> 二维数组转化作json
  详细解决方案

二维数组转化作json

热度:707   发布时间:2013-10-27 15:21:50.0
二维数组转化为json

?

二维数组转化为json

?

  1. 例:?二维数组格式?1,手机进水,123,321,1,手机进水,123,321??
  2. /**??
  3. ?????*js数组转json??
  4. ?????*??
  5. ?????*/????
  6. ????function?arrayToJson(o)?{?????
  7. ????var?r?=?[];?????
  8. ????if?(typeof?o?==?"string")?return?"\""?+?o.replace(/([\'\"\\])/g,?"\\$1").replace(/(\n)/g,?"\\n").replace(/(\r)/g,?"\\r").replace(/(\t)/g,?"\\t")?+?"\"";?????
  9. ????if?(typeof?o?==?"object")?{?????
  10. ????if?(!o.sort)?{?????
  11. ????for?(var?i?in?o)?????
  12. ????r.push(i?+?":"?+?arrayToJson(o[i]));?????
  13. ????if?(!!document.all?&&?!/^\n?function\s*toString\(\)\s*\{\n?\s*\[native?code\]\n?\s*\}\n?\s*$/.test(o.toString))?{?????
  14. ????r.push("toString:"?+?o.toString.toString());?????
  15. ????}?????
  16. ????r?=?"{"?+?r.join()?+?"}";?????
  17. ????}?else?{?????
  18. ????for?(var?i?=?0;?i?<?o.length;?i++)?{?????
  19. ????r.push(arrayToJson(o[i]));?????
  20. ????}?????
  21. ????r?=?"["?+?r.join()?+?"]";?????
  22. ????}?????
  23. ????return?r;?????
  24. ????}?????
  25. ????return?o.toString();?????
  26. ????}????
  27. 调这个JS方法转化后???为??[["1","手机进水","123","321"],["1","手机进水","123","321"]]?
  28. 注:其实js二维数组array2d可以直接转换成这种格式$.toJSON(array2d)等多种方法;?
  29. 然后在Java里转化为具体的对象?,封装成你需要的格式就行了??
  30. JSON需要下载一个jar包:??
  31. 下载地址:http://code.alibabatech.com/svn/fastjson/repository/com/alibaba/fastjson/1.0.4/fastjson-1.0.4.jar??
  32. ??
  33. ??
  34. ????public?List?JsonToList(String?arr){??
  35. ????????List?relReceiveFaultList?=?new?ArrayList<RelChecklistFault>();??
  36. ????????com.alibaba.fastjson.JSONArray?mainArray=JSON.parseArray(arr);????
  37. ?????????for(int?i=0;i<?mainArray.size();i++){????
  38. ?????????????log.info("数组大小:"+mainArray.size());???
  39. ???????????????com.alibaba.fastjson.JSONArray?paramObject=(com.alibaba.fastjson.JSONArray)mainArray.get(i);????
  40. ???????????????RelChecklistFault??relChecklistFault=?new?RelChecklistFault();??
  41. ???????????????relChecklistFault.setFaultType(paramObject.get(0).toString());??
  42. ???????????????relChecklistFault.setFaultSymptom(paramObject.get(1).toString());??
  43. ???????????????relChecklistFault.setFaultCause(paramObject.get(2).toString());??
  44. ???????????????relChecklistFault.setSuggest(paramObject.get(3).toString());??
  45. ??????????????relReceiveFaultList.add(relChecklistFault);??
  46. ???????????}????
  47. ????????return?relReceiveFaultList;??
  48. ????} ?
  相关解决方案