日期:2014-05-16  浏览次数:20336 次

JSON--List集合转换成JSON对象

转发出处:http://www.cnblogs.com/xmaomao/p/3184542.html

本文个人收藏

1. 简单的手动放置 键值对 到JSONObject,然后在put到JSONArray对象里

List<Article> al = articleMng.find(f);
??????????? System.out.println(al.size());
??????????? HttpServletResponse hsr = ServletActionContext.getResponse();
??????????? if(null == al){
??????????????? return ;
??????????? }
??????????? for(Article a : al){
??????????????? System.out.println(a.getId()+a.getDescription()+a.getTitle());
??????????? }
??????????? JSONArray json = new JSONArray();
??????????? for(Article a : al){
??????????????? JSONObject jo = new JSONObject();
??????????????? jo.put("id", a.getId());
??????????????? jo.put("title", a.getTitle());
??????????????? jo.put("desc", a.getDescription());
??????????????? json.put(jo);
??????????? }
??????????? try {
??????????????? System.out.println(json.toString());
??????????????? hsr.setCharacterEncoding("UTF-8");
??????????????? hsr.getWriter().write(json.toString());
??????????? } catch (IOException e) {
??????????????? e.printStackTrace();
??????????? }

?

上述代码JSONArray是引入的org.json.JSONArray包

?

而用net.sf.json包下JSONArray的静态方法:fromObject(list) 这是网上大多是都是直接用此方法快捷转换JSON,但是对于Hibernate级联操作关联的对象,这个方法就会报错,如果将映射文件中的级联配置去掉就行了。

?

另外对于list的要求就是其中的元素是字符串或对象,否则JSON不知道你想要的是什么数据。

?

<many-to-one name="cmsent" column="comment_tid" class="com.fcms.cms.entity.CmsComment" 
        not-null="false" cascade="delete">

?

?

但是级联操作毕竟还是得存在,否则以后数据冗余、多余。

解决方法就是:JSONArray subMsgs = JSONArray.fromObject(object, config);

JsonConfig config = new JsonConfig();
??????? config.setJsonPropertyFilter(new PropertyFilter() {
??????????? public boolean apply(Object arg0, String arg1, Object arg2) {
???????????????? if (arg1.equals("article") ||arg1.equals("fans")) {
??????????????????????? return true;
??????????????????? } else {
??????????????????????? return false;
??????????????????? }
??????????? }
??????? });

说明:提供了一个过滤作用,如果遇到关联的对象时他会自动过滤掉,不去执行关联关联所关联的对象。这里我贴出我hibernate中的配置关系映射的代码帮助理解:

<!-- 配置话题和团体之间的关系 -->
??????? <many-to-one name="article" class="com.fcms.nubb.article" column="article_id"/>
???????
??????? <!-- 配置主题帖与回复的帖子之间的关系 -->
??????? <set name="subMessages" table="sub_message" inverse="true" cascade="all" lazy="false" order-by="date asc">
??????????? <key column="theme_id" />
??????????? <one-to-many class="bbs.po.SubMessage" />
??????? </set>

总结:

1. JSONArray subMsgs = JSONArray.fromObject(subMessages, config);其中config是可选的,当出现上面的情况是可以配置config参数,如果没有上面的那种需求就可以直接使用fromObject(obj)方法,它转换出来的就是标准的json对象格式的数据,如下:

{["attr", "content", ...}, ...]}

2. JSONObject jTmsg = JSONObject.fromObject(themeMessage, config);这是专门用来解析标准的pojo,或者map对象的,pojo对象的格式就不用说了,map的形式是这样的{"str", "str"}。

?

----------------------------------------------------------- ?分割 -------------------------------------