将JavaBean及List集合转换为JSON

由于我的那个GridPanel要求数据源提供的数据为JSON格式,而我用Hibernate查出来的要么是List集合要么就是JavaBean。要把这样的数据转成JSON格式我是手工拼出来的。可是我很懒,我想用更简单更快捷的方式把他们转成JSON,为了实现这种转换,就必须找到传说中的如下6个jar包。
commons-beanutils-1.7.0.jar
commons-collections-3.2.jar
commons-lang-2.0.jar
commons-logging-1.0.4.jar
ezmorph-1.0.2.jar
json-lib-2.2.2-jdk15.jar
在net.sf.json.*下为你提供了很多工具类。但是这个直接转换出来的JSON还不是我想要的最终效果,我还需要指定数据总数等,而且这种格式要被多次使用。于是自己写了个工具类,对其进行了简单的封装。

import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
public class Java2JSON {
public static JSONObject generate(List<?> list,int count) {
Map<String, Object> map = new Hashtable<String, Object>();
map.put("totalCount", count);
map.put("topics", list);
return JSONObject.fromObject(map);
}
public static JSONObject javabean2json(Object object) {
Map<String, Object> map = new Hashtable<String, Object>();
map.put("success", true);
map.put("data", object);
return JSONObject.fromObject(map);
}
}

转换的结果是JSONObject类型,调用该对象自身的toString()方法即可得到JSON语句。


除非另有声明,本站遵循【署名-非商业性使用-相同方式共享 3.0 共享协议】授权。

转载原创文章请注明,转载自:Neeke[http://www.ineeke.com]

本文链接: http://www.ineeke.com/archives/convertjavabeanandlisttojson/

2009年3月13日 | 归档于 ExtJS | 2 条评论
  1. 2009年12月25日 11:54 | #1

    要能贴出这几个jar包供下载就更好了,正在学ext,要将Map转成json数据,学习下…

发表评论

XHTML: 您可以使用这些标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">
n:-zy n:-zr n:-zan n:-xf n:-wx n:-tz n:-tt n:-ts n:-sy n:-st n:-ss n:-sk n:-qd n:-pz n:-lh n:-kun n:-ku n:-hx n:-hd n:-gt n:-gg n:-bz

NOTICE: You should type some Chinese word (like “你好”) in your comment to pass the spam-check, thanks for your patience!