JSON--List集合轉換成JSON對象

轉自:http://www.cnblogs.com/xmaomao/p/3184542.htmlhtml

1. 簡單的手動放置 鍵值對 到JSONObject,而後在put到JSONArray對象裏java

複製代碼
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包json

而用net.sf.json包下JSONArray的靜態方法:fromObject(list) 這是網上大可能是都是直接用此方法快捷轉換JSON,可是對於Hibernate級聯操做關聯的對象,這個方法就會報錯,若是將映射文件中的級聯配置去掉就好了。app

另外對於list的要求就是其中的元素是字符串或對象,不然JSON不知道你想要的是什麼數據。svn

<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);this

複製代碼
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中的配置關係映射的代碼幫助理解:spa

複製代碼
<!-- 配置話題和團體之間的關係 -->
        <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>
複製代碼

總結:hibernate

1. JSONArray subMsgs = JSONArray.fromObject(subMessages, config);其中config是可選的,當出現上面的狀況是能夠配置config參數,若是沒有上面的那種需求就能夠直接使用fromObject(obj)方法,它轉換出來的就是標準的json對象格式的數據,以下:code

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

2. JSONObject jTmsg = JSONObject.fromObject(themeMessage, config);這是專門用來解析標準的pojo,或者map對象的,pojo對象的格式就不用說了,map的形式是這樣的{"str", "str"}。

 

-----------------------------------------------------------  分割 -------------------------------------------------------------------------------------------

 對於JSONArray和JSON以前用到想吐了!!!

可是,最近發現個好東西--fastjson (阿里巴巴溫少寫的一個將Object轉爲json數據的工具包)

 

bean

複製代碼
package com.nubb.bean;

import java.io.Serializable;

public class Person implements Serializable{
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    private String address;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
    
}
複製代碼

 

JsonUtil

複製代碼
package com.nubb.test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.nubb.bean.Person;


public class JSONSerializer {
        private static final String DEFAULT_CHARSET_NAME = "UTF-8";

        public static <T> String serialize(T object) {
            return JSON.toJSONString(object);
        }

        public static <T> T deserialize(String string, Class<T> clz) {
            return JSON.parseObject(string, clz);
        }

        public static <T> T load(Path path, Class<T> clz) throws IOException {
            return deserialize(
                    new String(Files.readAllBytes(path), DEFAULT_CHARSET_NAME), clz);
        }

        public static <T> void save(Path path, T object) throws IOException {
            if (Files.notExists(path.getParent())) {
                Files.createDirectories(path.getParent());
            }
            Files.write(path,
                    serialize(object).getBytes(DEFAULT_CHARSET_NAME),
                    StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING);
        }
        
        public static void main(String[] args) {
            Person person1 = new Person();
            person1.setAddress("address");
            person1.setAge(11);
            person1.setName("amao");
            
            Person person2 = new Person();
            person2.setAddress("address");
            person2.setAge(11);
            person2.setName("amao");
            
            List<Person> lp = new ArrayList<Person>();
            lp.add(person1);
            lp.add(person2);
            System.out.println(serialize(lp));
        }
        
}
複製代碼

輸出:

[{"address":"address","age":11,"name":"amao"},{"address":"address","age":11,"name":"amao"}]

 

其中用到的一個jar包能夠去下載: http://pan.baidu.com/s/1nCqNV

相關文章
相關標籤/搜索