Java中json使用方法_動力節(jié)點Java學院整理
摘要:JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。它基于ECMAScript的一個子集。 JSON采用完全獨立于語言的文本格式,但是也使用了類似于C語言家族的習慣(包括C、C++、C#、Java、JavaScript、Perl、Python等)。這些特性使JSON成為理想的數(shù)據(jù)交換語言。 易于人閱讀和編寫,同時也易于機器解析和生成(網(wǎng)絡傳輸速率)。
一、準備工作
json是個非常重要的數(shù)據(jù)結(jié)構(gòu),在web開發(fā)中應用十分廣泛。我覺得每個人都應該好好的去研究一下json的底層實現(xiàn),分析一下json的相關內(nèi)容,希望大家能有所收獲。首先給大家說一下使用json前的準備工作,需要準備下面的六個jar包:
需要說明幾點:
(1)json-lib最新版本可以從這個地方下載:http://sourceforge.net/projects/json-lib/files/json-lib/
(2)ezmorph是一個簡單的java類庫,用于將一種bean轉(zhuǎn)換成另外一種bean。其動態(tài)bean的實現(xiàn)依賴于commons-beanutils包。ezmorph可以在這個地方下載源碼:http://sourceforge.net/projects/ezmorph/files/ezmorph/
(3)commons-beanutils是操作Java Bean的類庫,依賴于commons-collections。可以從這里下載:http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi
(4)commons-collections類庫是各種集合類和集合工具類的封裝??梢詮倪@里下載:http://commons.apache.org/proper/commons-collections/download_collections.cgi
二、語法相關
JSON 語法規(guī)則
JSON 語法是 JavaScript 對象表示法語法的子集。
數(shù)據(jù)在名稱/值對中
數(shù)據(jù)由逗號分隔
花括號保存對象
方括號保存數(shù)組
JSON 值
JSON 值可以是:
數(shù)字(整數(shù)或浮點數(shù))
字符串(在雙引號中)
邏輯值(true 或 false)
數(shù)組(在方括號中)
對象(在花括號中)
null
JSON有兩種表示結(jié)構(gòu)
對象和數(shù)組。
對象結(jié)構(gòu)以”{”大括號開始,以”}”大括號結(jié)束。中間部分由0或多個以”,”分隔的”key(關鍵字)/value(值)”對構(gòu)成,關鍵字和值之間以”:”分隔,語法結(jié)構(gòu)如代碼。
{ key1:value1, key2:value2, ... }
如
1.{"department":"產(chǎn)品研發(fā)","name":"小王","age":23}
其中關鍵字是字符串,而值可以是字符串,數(shù)值,true,false,null,對象或數(shù)組
數(shù)組結(jié)構(gòu)以”[”開始,”]”結(jié)束。中間由0或多個以”,”分隔的值列表組成,語法結(jié)構(gòu)如代碼。
[ { key1:value1, key2:value2 }, { key3:value3, key4:value4 } ]
如:
[{"department":"產(chǎn)品研發(fā)","name":"小王","age":23},{"department":"產(chǎn)品研發(fā)","name":"小王","age":23}]
三、Java中使用Json基本使用方法
整個工程目錄 如下 :
Employer.java如下
package com.bjpowernode.json; import net.sf.json.JSONString; public class Employer { private String name; private Integer age; private String department; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } @Override public String toString() { return "Employer [name=" + name + ", age=" + age + ", department=" + department + "]"; } /* @Override 要調(diào)用這個方法請implements JSONString public String toJSONString() { return "{\"name\":\"" + name + "\",\"department\":\"" + department + "\"}"; }*/ }
JsonTest.java全部代碼如下:
package com.bjpowernode.json; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.util.PropertyFilter; /** *Json使用方法總結(jié) *@author linbingwen(博客:http://blog.csdn.net/evankaka) *@since 2015.7.3 */ public class JsonTest { public static void main(String args[]){ beanToJson(); beanToJson1(); beanToJson2(); arrayToJson(); listToJson(); mapToJson(); } /** * bean對象轉(zhuǎn)json * @return void */ public static void beanToJson(){ Employer employer=new Employer(); employer.setName("小王"); employer.setAge(23); employer.setDepartment("產(chǎn)品研發(fā)"); JSONObject json = JSONObject.fromObject(employer); System.out.println("-----------------------------------------beanToJson() 開始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------beanToJson() 結(jié)束------------------------------------------------"); } /** * bean對象轉(zhuǎn)json,帶過濾器 * @return void */ public static void beanToJson1(){ Employer employer=new Employer(); employer.setName("小王"); employer.setAge(23); employer.setDepartment("產(chǎn)品研發(fā)"); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes(new String[] { "age" }); JSONObject json = JSONObject.fromObject(employer, jsonConfig); System.out.println("-----------------------------------------beanToJson1()帶過濾器 開始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------beanToJson1()帶過濾器 結(jié)束------------------------------------------------"); } /** * bean對象轉(zhuǎn)json,帶過濾器 * @return void */ public static void beanToJson2(){ Employer employer=new Employer(); employer.setName("小王"); employer.setAge(23); employer.setDepartment("產(chǎn)品研發(fā)"); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { return source instanceof Employer && name.equals("age"); } }); JSONObject json = JSONObject.fromObject(employer, jsonConfig); System.out.println("-----------------------------------------beanToJson2() 帶過濾器 開始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------beanToJson2() 帶過濾器 結(jié)束------------------------------------------------"); } /** * array對象轉(zhuǎn)json * @return void */ public static void arrayToJson(){ Employer employer1=new Employer(); employer1.setName("小王"); employer1.setAge(23); employer1.setDepartment("產(chǎn)品研發(fā)"); Employer employer2=new Employer(); employer2.setName("小王"); employer2.setAge(23); employer2.setDepartment("產(chǎn)品研發(fā)"); Employer[] employers=new Employer[]{employer1,employer2}; JSONArray json = JSONArray.fromObject(employers); System.out.println("-----------------------------------------arrayToJson() 開始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------arrayToJson() 結(jié)束------------------------------------------------"); } /** * list對象轉(zhuǎn)json * @return void */ public static void listToJson(){ List<String> list = new ArrayList<String>(); list.add( "first" ); list.add( "second" ); JSONArray json = JSONArray.fromObject(list); System.out.println("-----------------------------------------listToJson() 開始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------listToJson() 結(jié)束------------------------------------------------"); } /** * map對象轉(zhuǎn)json * @return void */ public static void mapToJson(){ Map<Object,Object> map = new HashMap<Object,Object>(); map.put("name", "json"); map.put("bool", Boolean.TRUE); map.put("int", new Integer(1)); map.put("arr", new String[] { "a", "b" }); map.put("func", "function(i){ return this.arr[i]; }"); JSONObject json = JSONObject.fromObject(map); System.out.println("-----------------------------------------mapToJson() 開始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------mapToJson() 結(jié)束------------------------------------------------"); } }
下面分別對各個部分來進行說明
1. Bean轉(zhuǎn)換成json代碼
/** * bean對象轉(zhuǎn)json * @return void */ public static void beanToJson(){ Employer employer=new Employer(); employer.setName("小王"); employer.setAge(23); employer.setDepartment("產(chǎn)品研發(fā)"); JSONObject json = JSONObject.fromObject(employer); System.out.println("-----------------------------------------beanToJson() 開始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------beanToJson() 結(jié)束------------------------------------------------"); }
運行結(jié)果如下:
2. 數(shù)組轉(zhuǎn)換成json代碼
/** * array對象轉(zhuǎn)json * @return void */ public static void arrayToJson(){ Employer employer1=new Employer(); employer1.setName("小王"); employer1.setAge(23); employer1.setDepartment("產(chǎn)品研發(fā)"); Employer employer2=new Employer(); employer2.setName("小王"); employer2.setAge(23); employer2.setDepartment("產(chǎn)品研發(fā)"); Employer[] employers=new Employer[]{employer1,employer2}; JSONArray json = JSONArray.fromObject(employers); System.out.println("-----------------------------------------arrayToJson() 開始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------arrayToJson() 結(jié)束------------------------------------------------"); }
運行結(jié)果如下:
3. List集合轉(zhuǎn)換成json方法
/** * list對象轉(zhuǎn)json * @return void */ public static void listToJson(){ List<String> list = new ArrayList<String>(); list.add( "first" ); list.add( "second" ); JSONArray json = JSONArray.fromObject(list); System.out.println("-----------------------------------------listToJson() 開始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------listToJson() 結(jié)束------------------------------------------------"); }
運行結(jié)果如下:
4. Map集合轉(zhuǎn)換成json方法
/** * map對象轉(zhuǎn)json * @return void */ public static void mapToJson(){ Map<Object,Object> map = new HashMap<Object,Object>(); map.put("name", "json"); map.put("bool", Boolean.TRUE); map.put("int", new Integer(1)); map.put("arr", new String[] { "a", "b" }); map.put("func", "function(i){ return this.arr[i]; }"); JSONObject json = JSONObject.fromObject(map); System.out.println("-----------------------------------------mapToJson() 開始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------mapToJson() 結(jié)束------------------------------------------------"); }
運行結(jié)果如下:
四、JSONObject的過濾設置
通常對一個json串和java對象進行互轉(zhuǎn)時,經(jīng)常會有選擇性的過濾掉一些屬性值。例如下面的類:
package com.bjpowernode.json; public class Employer { private String name; private Integer age; private String department; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } @Override public String toString() { return "Employer [name=" + name + ", age=" + age + ", department=" + department + "]"; } }
如果我想過濾age屬性怎么辦?
方法一:實現(xiàn)JSONString接口
package com.bjpowernode.json; import net.sf.json.JSONString; public class Employer implements JSONString{ private String name; private Integer age; private String department; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } @Override public String toString() { return "Employer [name=" + name + ", age=" + age + ", department=" + department + "]"; } @Override public String toJSONString() { return "{\"name\":\"" + name + "\",\"department\":\"" + department + "\"}"; } }
方法二:設置jsonconfig實例,對包含和需要排除的屬性進行添加或刪除。
/** * bean對象轉(zhuǎn)json,帶過濾器 * @return void */ public static void beanToJson1(){ Employer employer=new Employer(); employer.setName("小王"); employer.setAge(23); employer.setDepartment("產(chǎn)品研發(fā)"); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes(new String[] { "age" }); JSONObject json = JSONObject.fromObject(employer, jsonConfig); System.out.println("-----------------------------------------beanToJson1()帶過濾器 開始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------beanToJson1()帶過濾器 結(jié)束------------------------------------------------"); }
方法三:使用propertyFilter實例過濾屬性
/** * bean對象轉(zhuǎn)json,帶過濾器 * @return void */ public static void beanToJson2(){ Employer employer=new Employer(); employer.setName("小王"); employer.setAge(23); employer.setDepartment("產(chǎn)品研發(fā)"); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { return source instanceof Employer && name.equals("age"); } }); JSONObject json = JSONObject.fromObject(employer, jsonConfig); System.out.println("-----------------------------------------beanToJson2() 帶過濾器 開始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------beanToJson2() 帶過濾器 結(jié)束------------------------------------------------"); }
五、JavaScript中使用JSON
JSON 最常見的用法之一,是從 web 服務器上讀取 JSON 數(shù)據(jù)(作為文件或作為 HttpRequest),將 JSON 數(shù)據(jù)轉(zhuǎn)換為 JavaScript 對象,然后在網(wǎng)頁中使用該數(shù)據(jù)。
之前我一直有個困惑,分不清普通字符串
1、json字符串和json對象的區(qū)別。
字符串:這個很好解釋,指使用“”雙引號或''單引號包括的字符。例如:var comStr = 'this is string';
json字符串:指的是符合json格式要求的js字符串。例如:var jsonStr = "{StudentID:'100',Name:'tmac',Hometown:'usa'}";
json對象:指符合json格式要求的js對象。例如:var jsonObj = { StudentID: "100", Name: "tmac", Hometown: "usa" };
2、JSON 實例 - 來自字符串的對象
創(chuàng)建包含 JSON 語法的 JavaScript 字符串:
var txt = '{ "employees" : [' + '{ "firstName":"John" , "lastName":"Doe" },' + '{ "firstName":"Anna" , "lastName":"Smith" },' + '{ "firstName":"Peter" , "lastName":"Jones" } ]}';
由于 JSON 語法是 JavaScript 語法的子集,JavaScript 函數(shù) eval() 可用于將 JSON 文本轉(zhuǎn)換為 JavaScript 對象。eval() 函數(shù)使用的是 JavaScript 編譯器,可解析 JSON 文本,然后生成 JavaScript 對象。必須把文本包圍在括號中,這樣才能避免語法錯誤:
var obj = eval ("(" + txt + ")");
如下格式:
<!DOCTYPE html> <html> <body> <h2>Create Object from JSON String</h2> <p> First Name: <span id="fname"></span><br> Last Name: <span id="lname"></span><br> </p> <script> var txt = '{"employees":[' + '{"firstName":"John","lastName":"Doe" },' + '{"firstName":"Anna","lastName":"Smith" },' + '{"firstName":"Peter","lastName":"Jones" }]}'; var obj = eval ("(" + txt + ")"); document.getElementById("fname").innerHTML=obj.employees[1].firstName document.getElementById("lname").innerHTML=obj.employees[1].lastName </script> </body> </html>
輸出結(jié)果:
不過eval解析json有安全隱患!現(xiàn)在大多數(shù)瀏覽器(IE8及以上,Chrome和Firefox差不多全部)自帶原生JSON對象,提供JSON.parse()方法解析JSON,提供JSON.stringify()方法生成JSON,請使用這兩個方法!
如果擔心parse()對對象拋異常,可以加一個封裝函數(shù):
JSON.pParse = function( tar ) { if( typeof( tar ) === 'string' ) { return JSON.parse( tar ); } else { return tar; } };
1、從JSON中讀數(shù)據(jù)
//1,從JSON中讀數(shù)據(jù) function ReadJSON() { alert(obj.key1); alert(obj.key2); alert(obj.person[0].name); //或者alert(obj.person[0]["name"]) alert(obj.object.msg); //或者alert(obj.object["msg"]) }
2、增加JSON中的數(shù)據(jù)
function Add() { //往JSON對象中增加了一條記錄 obj.sex= "男" //或者obj["sex"]="男" alert(obj.sex); }
3、更新JSON中的數(shù)據(jù)
function Update() { obj.count = 10; //或obj["count"]=10 }
4、刪除JSON中的數(shù)據(jù)
function Delete() { delete obj.count; } 、遍歷JSON中的數(shù)據(jù) function Traversal() { for (var c in obj) { console.log(c + ":", obj[c]); } }
六、XML與JSON對比
XML定義
擴展標記語言 (Extensible Markup Language, XML),用于標記電子文件使其具有結(jié)構(gòu)性的標記語言,可以用來標記數(shù)據(jù)、定義數(shù)據(jù)類型,是一種允許用戶對自己的標記語言進行定義的源語言。XML使用DTD(document type definition)文檔類型定義來組織數(shù)據(jù);?格式統(tǒng)一,跨平臺和語言,早已成為業(yè)界公認的標準。
XML是標準通用標記語言(SGML) 的子集,非常適合Web 傳輸。XML提供統(tǒng)一的方法來描述和交換獨立于應用程序或供應商的結(jié)構(gòu)化數(shù)據(jù)。
JSON定義
JSON(JavaScript Object Notation)一種輕量級的數(shù)據(jù)交換格式,具有良好的可讀和便于快速編寫的特性。可在不同平臺之間進行數(shù)據(jù)交換。JSON采用兼容性很高的、完全獨立于語言文本格式,同時也具備類似于C語言的習慣(包括C, C++, C#, Java, JavaScript, Perl, Python等)體系的行為。這些特性使JSON成為理想的數(shù)據(jù)交換語言。
JSON基于JavaScript Programming Language , Standard ECMA-262 3rd Edition - December 1999的一個子集。
XML和JSON優(yōu)缺點
(1).XML的優(yōu)缺點
<1>.XML的優(yōu)點
A.格式統(tǒng)一,符合標準;
B.容易與其他系統(tǒng)進行遠程交互,數(shù)據(jù)共享比較方便。
<2>.XML的缺點
A.XML文件龐大,文件格式復雜,傳輸占帶寬;
B.服務器端和客戶端都需要花費大量代碼來解析XML,導致服務器端和客戶端代碼變得異常復雜且不易維護;
C.客戶端不同瀏覽器之間解析XML的方式不一致,需要重復編寫很多代碼;D.服務器端和客戶端解析XML花費較多的資源和時間。
JSON的優(yōu)缺點
<1>.JSON的優(yōu)點:
A.數(shù)據(jù)格式比較簡單,易于讀寫,格式都是壓縮的,占用帶寬小;B.易于解析,客戶端JavaScript可以簡單的通過eval()進行JSON數(shù)據(jù)的讀取;C.支持多種語言,包括ActionScript, C, C#, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby等服務器端語言,便于服務器端的解析;D.在PHP世界,已經(jīng)有PHP-JSON和JSON-PHP出現(xiàn)了,偏于PHP序列化后的程序直接調(diào)用,PHP服務器端的對象、數(shù)組等能直接生成JSON格式,便于客戶端的訪問提取;E.因為JSON格式能直接為服務器端代碼使用,大大簡化了服務器端和客戶端的代碼開發(fā)量,且完成任務不變,并且易于維護。
<2>.JSON的缺點
A.沒有XML格式這么推廣的深入人心和喜用廣泛,沒有XML那么通用性;
B.JSON格式目前在Web Service中推廣還屬于初級階段。
相關文章
AsyncHttpClient?ClientStats源碼流程解讀
這篇文章主要為大家介紹了AsyncHttpClient?ClientStats源碼流程解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12SpringCloud實戰(zhàn)之Feign聲明式服務調(diào)用
這篇文章主要介紹了SpringCloud實戰(zhàn)之Feign聲明式服務調(diào)用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05關于java入門與java開發(fā)環(huán)境配置詳細教程
這篇文章主要介紹了關于java入門與java開發(fā)環(huán)境配置詳細教程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03