java--List转换成json格式


方法一

首先导入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.add(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。

猜你喜欢

转载自blog.csdn.net/qq_40435659/article/details/79866660