JSON--List集合轉(zhuǎn)換成JSON對象詳解
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的靜態(tài)方法:fromObject(list) 這是網(wǎng)上大多是都是直接用此方法快捷轉(zhuǎn)換JSON,但是對于Hibernate級聯(lián)操作關(guān)聯(lián)的對象,這個方法就會報錯,如果將映射文件中的級聯(lián)配置去掉就行了。
另外對于list的要求就是其中的元素是字符串或?qū)ο?,否則JSON不知道你想要的是什么數(shù)據(jù)。
<many-to-one name="cmsent" column="comment_tid" class="com.fcms.cms.entity.CmsComment" not-null="false" cascade="delete">
但是級聯(lián)操作畢竟還是得存在,否則以后數(shù)據(jù)冗余、多余。
解決方法就是: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; } } });
說明:提供了一個過濾作用,如果遇到關(guān)聯(lián)的對象時他會自動過濾掉,不去執(zhí)行關(guān)聯(lián)關(guān)聯(lián)所關(guān)聯(lián)的對象。這里我貼出我hibernate中的配置關(guān)系映射的代碼幫助理解:
<!-- 配置話題和團(tuán)體之間的關(guān)系 --> <many-to-one name="article" class="com.fcms.nubb.article" column="article_id"/> <!-- 配置主題帖與回復(fù)的帖子之間的關(guān)系 --> <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>
總結(jié):
1. JSONArray subMsgs = JSONArray.fromObject(subMessages, config);其中config是可選的,當(dāng)出現(xiàn)上面的情況是可以配置config參數(shù),如果沒有上面的那種需求就可以直接使用fromObject(obj)方法,它轉(zhuǎn)換出來的就是標(biāo)準(zhǔn)的json對象格式的數(shù)據(jù),如下:
{["attr", "content", ...}, ...]}
2. JSONObject jTmsg = JSONObject.fromObject(themeMessage, config);這是專門用來解析標(biāo)準(zhǔn)的pojo,或者map對象的,pojo對象的格式就不用說了,map的形式是這樣的{"str", "str"}。
---------------------------------------------------------- 分割 -------------------------------------------------------------------------------------------
對于JSONArray和JSON之前用到想吐了?。。?/p>
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"}]
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
為什么mybatis中的SqlSession一定要關(guān)閉
這篇文章主要介紹了為什么mybatis中的SqlSession一定要關(guān)閉,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12Java實戰(zhàn)項目練習(xí)之球館在線預(yù)約系統(tǒng)的實現(xiàn)
理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SpringBoot+maven+freemark+Mysql實現(xiàn)一個球館在線預(yù)約系統(tǒng),大家可以在過程中查缺補漏,提升水平2022-01-01spring boot使用logback日志級別打印控制操作
這篇文章主要介紹了spring boot使用logback日志級別打印控制操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03springboot整合jsp,實現(xiàn)公交車站路線圖
這篇文章主要介紹了springboot整合jsp,實現(xiàn)公交車站路線圖的步驟,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下2021-01-01