<%@ page import="net.sf.json.JSONObject"%>
<%
//json的数组遍历方法
String forms="{"fields":[{"field_id":"1","field_name":"aaa","field_title":"字段一","field_type":"text","field_value":"aaa"},{"field_id":"2","field_name":"bbbb","field_title":"字段二","field_type":"select","field_value":"一一,在在,大枯"},{"field_id":"3","field_name":"ccc","field_title":"字段三","field_type":"radio","field_value":"aa,bb,cc"},{"field_id":"4","field_name":"dddd","field_title":"字段四","field_type":"checkbox","field_value":"济南,北京,上海"},{"field_id":"5","field_name":"eee","field_title":"字段五","field_type":"textarea","field_value":""},{"field_id":"6","field_name":"fff","field_title":"字段六","field_type":"image","field_value":"/images/nopic.gif"},{"field_id":"7","field_name":"ggg","field_title":"字段七","field_type":"datetime","field_value":""},{"field_id":"8","field_name":"hhh","field_title":"字段八","field_type":"editor","field_value":"test在"},]}";
jb = JSONObject.fromObject(forms);
ja = jb.getJSONArray("fields");
if(ja!=null){
for (int i = 0; i < ja.size(); i++) {
sb.append("{");
sb.append("\"field_id\":\""+ja.getJSONObject(i).getString("field_id")+"\",");
sb.append("\"field_name\":\""+ja.getJSONObject(i).getString("field_name")+"\",");
sb.append("\"field_title\":\""+ja.getJSONObject(i).getString("field_title")+"\",");
sb.append("\"field_type\":\""+ja.getJSONObject(i).getString("field_type")+"\",");
sb.append("\"field_value\":\""+ja.getJSONObject(i).getString("field_value")+"\"");
sb.append("}");
sb.append(",");
}
}
%>
另外关于json的遍历代码如下:
import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; public class Test3 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String s="【Object json树形字符串】"; Map map=new HashMap(); JsonConfig jc=new JsonConfig(); jc.setClassMap(map); jc.setRootClass(Map.class); jc.setArrayMode(JsonConfig.MODE_LIST); JSONObject jobj=JSONObject.fromObject(s,jc); //递归遍历 decodeJSONObject(jobj); } public static void decodeJSONObject(JSONObject json){ Iterator<String> keys=json.keys(); JSONObject jo=null; Object o; String key; while(keys.hasNext()){ key=keys.next(); o=json.get(key); if(o instanceof JSONObject){ jo=(JSONObject)o; if(jo.keySet().size()>0){ decodeJSONObject(jo); }else{ System.out.println(key); } }else{ System.out.println(o); } } } }