method one
First import the jar package, 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.add(jo); } return json; }
Converting list to json is very similar to the operation of map in java.
Method Two
The second method is simpler. There are no steps similar to the map operation. You only need to import the relevant jar package, and you can call the existing function fromObject(), the parameter input list, and the return value is json. The jar package is as follows:
commons-beanutils-1.7.jar commons-collections.jar commons-lang.jar ezmorph.jar json-lib-2.2.2-jdk15.jar
Example:
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; } }
Note that the JSONArray imported by this example is net.sf.json.JSONArray, and the one imported above is org.json.JSONArray.