方法一
首先導入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.jar commons-collections.jar commons-lang.jar ezmorph.jar json-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。