JSON簡介及JSONObject產生json

來源:互聯網
上載者:User

標籤:

一、JSON簡介

JSON:JavaScript對象標記法(JavaScript Object Notation)

類似xml  :儲存和交換資訊的文法

比xml更快、更易解析

JSON文法規則:

  1、資料在成對的名稱和數值中

  2、資料有逗號分隔

  3、花括弧儲存對象

  4、方括弧儲存數組

JSON值:

  1、數字:整數或浮點數

  2、字串:在雙引號中

  3、邏輯值:true false

  4、數組:在方括弧中

  5、對象:在花括弧中

  6、null

二、在JAVA中使用JSONObject產生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(map);
System.out.println(json.toString()); //結果為:{"name":"hzucmj","age":22}

 本文部分轉載至:http://blog.csdn.net/ygzk123/article/details/8273293

JSON簡介及JSONObject產生json

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.