方法一
首先导入jar包,json-rpc-1.0.jar
public class List2Json {public static JSONArray ProLogList2Json(List<ProgramLog> list){JSONArray json = new JSONArray();for(ProgramLog pLog : list){JSONObject jo = new JSONObject();jo.put("id", pLog.getId());jo.put("time", pLog.getBeginTime());json.put(jo);}return json;}
list转换成json很像是java对map的操作。
方法二
第二种方法更加简单,没有类似map操作的步骤,只需要引入相关jar包,就可以调用已有的函数fromObject(),其参数输入list,其返回值就是json。jar包如下:
commons-beanutils-1.7.jarcommons-collections.jarcommons-lang.jarezmorph.jarjson-lib-2.2.2-jdk15.jar
实例:
import java.util.List;import net.sf.json.JSONArray;import com.test.vo.ProgramLog;public class List2Json1 {public static JSONArray List2Json(List<ProgramLog> list){JSONArray json = JSONArray.fromObject(list);return json;}}
注意这个实例导入的JSONArray是net.sf.json.JSONArray,上边的导入的是org.json.JSONArray。