在JAVA中使用JSONObject產生json

來源:互聯網
上載者:User

JSON是一種輕量級的資料交換格式,在現在的web開發中,是非常常見的。在沒有方便的工具之前,我們或許會使用拼字串的形式來產生json數組,今天我們使用一個json-lib.jar包來為我們實現產生json的功能。

所必須的包有:

commons-httpclient-3.1.jar

commons-lang-2.4.jar

commons-logging-1.1.1.jar

json-lib-2.4-jdk15.jar

ezmorph-1.0.6.jar

commons-collections-3.2.1.jar

 1、bean轉為Json

User u = new User();
u.setAge(22);
u.setUsername("hzucmj");
u.setEnabled(true);

JSONObject json = JSONObject.fromObject(u);
System.out.println(json.toString()); //結果為:{"enabled":true,"username":"hzucmj","age":22}

2、List轉為Json

User u1 = new User();
u1.setAge(22);
u1.setUsername("hzucmj");
u1.setEnabled(true);

User u2 = new User();
u2.setAge(20);
u2.setUsername("ctf");
u2.setEnabled(true);

List<Object> list = new ArrayList<Object>();
list.add(u1);</p>
list.add(u2);</p>

JSONArray json = JSONArray.fromObject(list);
System.out.println(json.toString()); //結果為:[{"enabled":false,"username":"ctf","age":20},{"enabled":false,"username":"","age":0}]

3、Map轉為Json

HashMap<String, Comparable> map = new HashMap<String, Comparable>();
map.put("name", "hzucmj");
map.put("age", 22);
JSONObject json = JSONObject.fromObject(list);
System.out.println(json.toString()); //結果為:{"name":"hzucmj","age":22}

通過json-lib提供給我們的方法,實現json數組的產生就變得很簡單了,當然,json-lib提供的也不僅僅是這些方法而已,還有其它一些方法大家可以好好研究研究啊。

來自:hzucmj.com

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.