1. 程式人生 > >json 轉list 集合

json 轉list 集合

好久沒寫部落格 了,雖然寫的一塌糊塗吧,但也得堅持。今天遇到json 轉list集合的問題,隨便就記一下

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

pom.xml 檔案:

        <!-- json依賴 -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
<classifier>jdk15</classifier> </dependency> <dependency> <groupId>net.sf.ezmorph</groupId> <artifactId>ezmorph</artifactId> </dependency> <dependency> <groupId>
commons-collections</groupId> <artifactId>commons-collections</artifactId> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> </dependency
>
<!-- json依賴 end --> 對應版本 <json-lib.version>2.4</json-lib.version> <ezmorph.version>1.0.6</ezmorph.version> <commons-collections.version>3.2.1</commons-collections.version> <commons-beanutils.version>1.9.3</commons-beanutils.version>

java

customized 值為: [{“cusId”:”999”,”orderNum”:1},{“cusId”:”998”,”orderNum”:2}]

String customized = " [{\"cusId\":\"999\",\"orderNum\":1},{\"cusId\":\"998\",\"orderNum\":2}]"


List<Customized> list1 = new ArrayList();  
// 先把json 字串轉換為json 陣列
        JSONArray jsonArray1 = JSONArray.fromObject(customized);  
//迴圈獲取json陣列中的 json 物件,然後轉換為 object
        for (int i = 0; i < jsonArray1.size(); i++) {  
            JSONObject jsonObject2 = jsonArray1.getJSONObject(i);  
            Customized cust = (Customized) JSONObject.toBean(jsonObject2, Customized.class);  
            list1.add(cust);  
        }  

json 字串中的屬性 必須 和 Customized 物件中的屬性一一對應