javascript
Google Gson的使用方法及JSON 技术对比
為什么80%的碼農(nóng)都做不了架構(gòu)師?>>> ??
? 一 、各個JSON技術(shù)的簡介和優(yōu)劣
?
1.json-lib
json-lib最開始的也是應(yīng)用最廣泛的json解析工具,json-lib 不好的地方確實(shí)是依賴于很多第三方包,
包括commons-beanutils.jar,commons-collections-3.2.jar,commons-lang-2.6.jar,commons-logging-1.1.1.jar,ezmorph-1.0.6.jar,對于復(fù)雜類型的轉(zhuǎn)換,json-lib對于json轉(zhuǎn)換成bean還有缺陷,比如一個類里面會出現(xiàn)另一個類的list或者map集合,json-lib從json到bean的轉(zhuǎn)換就會出現(xiàn)問題。json-lib在功能和性能上面都不能滿足現(xiàn)在互聯(lián)網(wǎng)化的需求。
2.開源的Jackson
相比json-lib框架,Jackson所依賴的jar包較少,簡單易用并且性能也要相對高些。而且Jackson社區(qū)相對比較活躍,更新速度也比較快。Jackson對于復(fù)雜類型的json轉(zhuǎn)換bean會出現(xiàn)問題,一些集合Map,List的轉(zhuǎn)換出現(xiàn)問題。Jackson對于復(fù)雜類型的bean轉(zhuǎn)換Json,轉(zhuǎn)換的json格式不是標(biāo)準(zhǔn)的Json格式
3.Google的Gson
Gson是目前功能最全的Json解析神器,Gson當(dāng)初是為因應(yīng)Google公司內(nèi)部需求而由Google自行研發(fā)而來,
但自從在2008年五月公開發(fā)布第一版后已被許多公司或用戶應(yīng)用。Gson的應(yīng)用主要為toJson與fromJson兩個轉(zhuǎn)換函數(shù),無依賴,不需要例外額外的jar,能夠直接跑在JDK上。而在使用這種對象轉(zhuǎn)換之前需先創(chuàng)建好對象的類型以及其成員才能成功的將JSON字符串成功轉(zhuǎn)換成相對應(yīng)的對象。類里面只要有g(shù)et和set方法,Gson完全可以將復(fù)雜類型的json到bean或bean到j(luò)son的轉(zhuǎn)換,是JSON解析的神器。Gson在功能上面無可挑剔,但是性能上面比FastJson有所差距。
4.阿里巴巴的FastJson
Fastjson是一個Java語言編寫的高性能的JSON處理器,由阿里巴巴公司開發(fā)。無依賴,不需要例外額外的jar,能夠直接跑在JDK上。FastJson在復(fù)雜類型的Bean轉(zhuǎn)換Json上會出現(xiàn)一些問題,可能會出現(xiàn)引用的類型,導(dǎo)致Json轉(zhuǎn)換出錯,需要制定引用。FastJson采用獨(dú)創(chuàng)的算法,將parse的速度提升到極致,超過所有json庫。
綜上4種Json技術(shù)的比較,在項(xiàng)目選型的時候可以使用Google的Gson和阿里巴巴的FastJson兩種并行使用,如果只是功能要求,沒有性能要求,可以使用google的Gson,如果有性能上面的要求可以使用Gson將bean轉(zhuǎn)換json確保數(shù)據(jù)的正確,使用FastJson將Json轉(zhuǎn)換Bean
?
二、Google的Gson包的使用簡介。
Gson類:解析json的最基礎(chǔ)的工具類
JsonParser類:解析器來解析JSON到JsonElements的解析樹
JsonElement類:一個類代表的JSON元素
JsonObject類:JSON對象類型
JsonArray類:JsonObject數(shù)組
TypeToken類:用于創(chuàng)建type,比如泛型List<?>
maven 依賴:
<dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.7</version> </dependency>三、Gson的使用
首先定義一個類:
package com.test;import java.util.Date;public class User {private Integer id;private int age;private String userName;private Date birthday;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public User(Integer id, int age, String userName, Date birthday) {super();this.id = id;this.age = age;this.userName = userName;this.birthday = birthday;}public User() {super();}}測試實(shí)例:
package com.test;import java.util.Date; import java.util.List; import java.util.Set;import org.junit.Test;import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken;public class GsonTest {@Testpublic void test1() throws Exception {Gson gson = new Gson();User user = new User(1, 20, "AA", new Date());System.out.println("Bean->轉(zhuǎn)換為JSON字符串:");String jsonStr = gson.toJson(user);System.out.println(jsonStr);System.out.println();}@Testpublic void test2() throws Exception {Gson gson = new Gson();String jsonStr = "{\"id\":1,\"age\":20,\"userName\":\"AA\",\"birthday\":\"Nov 14, 2016 4:52:38 PM\"}";System.out.println("字符串->轉(zhuǎn)換成Bean對象");User user = gson.fromJson(jsonStr, User.class);System.out.println(user);System.out.println();}@Testpublic void test3() throws Exception {Gson gson = new Gson();System.out.println("json轉(zhuǎn)換復(fù)雜的bean,比如List,Set,Map:");String json = "[{\"id\":\"1\",\"name\":\"Json技術(shù)\"},{\"id\":\"2\",\"name\":\"java技術(shù)\"}]";List list = gson.fromJson(json, new TypeToken<List>() {}.getType());Set set = gson.fromJson(json, new TypeToken<Set>() {}.getType());System.out.println();}@Testpublic void test4() throws Exception {Gson gson = new Gson();String json = "[{\"id\":\"1\",\"name\":\"Json技術(shù)\"},{\"id\":\"2\",\"name\":\"java技術(shù)\"}]";System.out.println("格式化JSON:");gson = new GsonBuilder().setPrettyPrinting().create();JsonParser jp = new JsonParser();JsonElement je = jp.parse(json);json = gson.toJson(je);System.out.println(json);System.out.println();}@Testpublic void test5() throws Exception {System.out.println("判斷字符串是否是json,通過捕捉的異常來判斷是否是json");String json = "[{\"id\":\"1\",\"name\":\"Json技術(shù)\"},{\"id\":\"2\",\"name\":\"java技術(shù)\"}]";boolean jsonFlag;try {new JsonParser().parse(json).getAsJsonObject();jsonFlag = true;} catch (Exception e) {jsonFlag = false;}System.out.println(jsonFlag + ":" + jsonFlag);System.out.println();}@Testpublic void test6() throws Exception {System.out.println("從json串中獲取屬性");String json = "{\"id\":\"1\",\"name\":\"Json技術(shù)\"}";String propertyName = "name";String propertyValue = "";try {JsonParser jsonParser = new JsonParser();JsonElement element = jsonParser.parse(json);JsonObject jsonObj = element.getAsJsonObject();propertyValue = jsonObj.get(propertyName).toString();System.out.println("propertyValue:" + propertyValue);} catch (Exception e) {propertyValue = null;}System.out.println();}@Testpublic void test7() throws Exception {System.out.println("除去json中的某個屬性");String json = "{\"id\":\"1\",\"name\":\"Json技術(shù)\"}";String propertyName = "id";JsonParser jsonParser = new JsonParser();JsonElement element = jsonParser.parse(json);JsonObject jsonObj = element.getAsJsonObject();jsonObj.remove(propertyName);json = jsonObj.toString();System.out.println("json:" + json);System.out.println();}@Testpublic void test8() throws Exception {System.out.println("向json中添加屬性");String json = "{\"id\":\"1\",\"name\":\"Json技術(shù)\"}";String propertyName = "desc";Object propertyValue = "json各種技術(shù)的調(diào)研";JsonParser jsonParser = new JsonParser();JsonElement element = jsonParser.parse(json);JsonObject jsonObj = element.getAsJsonObject();jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue));json = jsonObj.toString();System.out.println("json:" + json);System.out.println();}@Testpublic void test9() throws Exception {System.out.println("修改json中的屬性");String json = "{\"id\":\"1\",\"name\":\"Json技術(shù)\"}";String propertyName = "name";Object propertyValue = "json各種技術(shù)的調(diào)研";JsonParser jsonParser = new JsonParser();JsonElement element = jsonParser.parse(json);JsonObject jsonObj = element.getAsJsonObject();jsonObj.remove(propertyName);jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue));json = jsonObj.toString();System.out.println("json:" + json);System.out.println();}@Testpublic void test10() throws Exception {System.out.println("判斷json中是否有屬性");String json = "{\"id\":\"1\",\"name\":\"Json技術(shù)\"}";String propertyName = "name";boolean isContains = false;JsonParser jsonParser = new JsonParser();JsonElement element = jsonParser.parse(json);JsonObject jsonObj = element.getAsJsonObject();isContains = jsonObj.has(propertyName);System.out.println("isContains:" + isContains);System.out.println();}@Testpublic void test11() throws Exception {System.out.println("json中日期格式的處理");GsonBuilder builder = new GsonBuilder();builder.setDateFormat("yyyy-MM-dd");Gson gson = builder.create();User user = new User();user.setBirthday(new Date());String json = gson.toJson(user);System.out.println("json:" + json);System.out.println();}@Testpublic void test12() throws Exception {System.out.println("json中對于Html的轉(zhuǎn)義");GsonBuilder builder = new GsonBuilder();builder.disableHtmlEscaping();Gson gson = builder.create();System.out.println();} }運(yùn)行如下:
判斷json中是否有屬性 isContains:truejson中日期格式的處理 json:{"age":0,"birthday":"2016-11-14"}json中對于Html的轉(zhuǎn)義Bean->轉(zhuǎn)換為JSON字符串: {"id":1,"age":20,"userName":"AA","birthday":"Nov 14, 2016 5:14:19 PM"}字符串->轉(zhuǎn)換成Bean對象 User [id=1, age=20, userName=AA, birthday=Mon Nov 14 16:52:38 CST 2016]json轉(zhuǎn)換復(fù)雜的bean,比如List,Set,Map:格式化JSON: [{"id": "1","name": "Json技術(shù)"},{"id": "2","name": "java技術(shù)"} ]判斷字符串是否是json,通過捕捉的異常來判斷是否是json false:false從json串中獲取屬性 propertyValue:"Json技術(shù)"除去json中的某個屬性 json:{"name":"Json技術(shù)"}向json中添加屬性 json:{"id":"1","name":"Json技術(shù)","desc":"\"json各種技術(shù)的調(diào)研\(zhòng)""}修改json中的屬性 json:{"id":"1","name":"\"json各種技術(shù)的調(diào)研\(zhòng)""}更多關(guān)于GSON的使用方法,請參考【這里面介紹的很詳細(xì)】:http://www.jianshu.com/p/e740196225a4
轉(zhuǎn)載于:https://my.oschina.net/hapier/blog/787565
總結(jié)
以上是生活随笔為你收集整理的Google Gson的使用方法及JSON 技术对比的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 错误:升级为xcode8之后无法上网的解
- 下一篇: Mediawiki随笔