javascript
用第三方工具类,将JavaBean、List、MapString,Object转成JSON文本
導入第三方jar包:
??? 》commons-beanutils-1.7.0.jar
??? 》commons-collections-3.1.jar
??? 》commons-lang-2.5.jar
??? 》commons-logging-1.1.1.jar
》ezmorph-1.0.3.jar
》json-lib-2.1-jdk15.jar????????????
?? (1)JavaBean->JSON
???????? ??? 》JSONArray jsonArray = JSONArray.fromObject(city);
???????? ??? 》String jsonJAVA = jsonArray.toString();
?? (2)List<JavaBean>->JSON
??????? 》JSONArray jsonArray = JSONArray.fromObject(cityList);
???????? ??? 》String jsonJAVA = jsonArray.toString();
?? (3)List<String>->JSON
??????? 》JSONArray jsonArray = JSONArray.fromObject(stringList);
???????? ??? 》String jsonJAVA = jsonArray.toString();
(4)Map<String,Object>->JSON【重點】
package loaderman.bean2json;import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;import net.sf.json.JSONArray;import org.junit.Test;/*** 演示用第三方工具類,將JavaBean、List、Map<String,Object>轉成JSON文本**/ public class TestJson {@Testpublic void javabean2json() {User user = new User(1, "哈哈", 123, "男");JSONArray jsonArray = JSONArray.fromObject(user);String jsonJAVA = jsonArray.toString();System.out.println(jsonJAVA);//[{"id":1,"name":"哈哈","sal":7000}] }@Testpublic void list2json() {List<User> userList = new ArrayList<User>();userList.add(new User(1, "恩和", 123, "男"));userList.add(new User(2, "恩和老婆", 123, "男"));userList.add(new User(3, "恩和小孩", 24, "男"));JSONArray jsonArray = JSONArray.fromObject(userList);String jsonJAVA = jsonArray.toString();System.out.println(jsonJAVA);//[{"id":1,"name":"恩和","sal":7000},{"id":2,"name":"福老婆","sal":8000},{"id":3,"name":"恩和","sal":20000}] }@Testpublic void map2json() {List<User> userList = new ArrayList<User>();userList.add(new User(1, "張三", 7000, "男"));userList.add(new User(2, "張三老婆", 8000, "女"));userList.add(new User(3, "張三小孩", 20000, "男"));userList.add(new User(4, "張三小孩的小孩", 40000, "男"));Map<String, Object> map = new HashMap<String, Object>();//total表示集合的長度map.put("total", userList.size());//rows表示集合內容map.put("rows", userList);JSONArray jsonArray = JSONArray.fromObject(map);String jsonJAVA = jsonArray.toString();System.out.println(jsonJAVA);jsonJAVA = jsonJAVA.substring(1, jsonJAVA.length() - 1);System.out.println(jsonJAVA);} }?
轉載于:https://www.cnblogs.com/loaderman/p/10059826.html
總結
以上是生活随笔為你收集整理的用第三方工具类,将JavaBean、List、MapString,Object转成JSON文本的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Lighting System Desi
- 下一篇: 1万小时贫穷定律:为什么你越忙越穷?