java--List converts to json format


method one

First import the jar package, json-rpc-1.0.jar

copy code
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;
    }
copy code

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:

copy code
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;
    }
}
copy code

Note that the JSONArray imported by this example is net.sf.json.JSONArray, and the one imported above is org.json.JSONArray.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326166966&siteId=291194637