javascript
gson解析天气json_几种常用JSON解析库性能比较
PS:公眾號推文時間工作日早晨8點50分,周末下午3點30分,不見不散哈!
作者:飛污熊
xncoding.com/2018/01/09/java/jsons.html
本篇通過JMH來測試一下Java中幾種常見的JSON解析庫的性能。?每次都在網(wǎng)上看到別人說什么某某庫性能是如何如何的好,碾壓其他的庫。但是百聞不如一見,只有自己親手測試過的才是最值得相信的。
JSON不管是在Web開發(fā)還是服務(wù)器開發(fā)中是相當常見的數(shù)據(jù)傳輸格式,一般情況我們對于JSON解析構(gòu)造的性能并不需要過于關(guān)心,除非是在性能要求比較高的系統(tǒng)。
目前對于Java開源的JSON類庫有很多種,下面我們?nèi)?個常用的JSON庫進行性能測試對比,?同時根據(jù)測試結(jié)果分析如果根據(jù)實際應(yīng)用場景選擇最合適的JSON庫。
這4個JSON類庫分別為:Gson,FastJson,Jackson,Json-lib。
簡單介紹
選擇一個合適的JSON庫要從多個方面進行考慮:
字符串解析成JSON性能
字符串解析成JavaBean性能
JavaBean構(gòu)造JSON性能
集合構(gòu)造JSON性能
易用性
先簡單介紹下四個類庫的身份背景
Gson
項目地址:https://github.com/google/gson
Gson是目前功能最全的Json解析神器,Gson當初是為因應(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完全可以實現(xiàn)復雜類型的json到bean或bean到j(luò)son的轉(zhuǎn)換,是JSON解析的神器。
FastJson
項目地址:https://github.com/alibaba/fastjson
Fastjson是一個Java語言編寫的高性能的JSON處理器,由阿里巴巴公司開發(fā)。無依賴,不需要例外額外的jar,能夠直接跑在JDK上。FastJson在復雜類型的Bean轉(zhuǎn)換Json上會出現(xiàn)一些問題,可能會出現(xiàn)引用的類型,導致Json轉(zhuǎn)換出錯,需要制定引用。FastJson采用獨創(chuàng)的算法,將parse的速度提升到極致,超過所有json庫。
Jackson
項目地址:https://github.com/FasterXML/jackson
Jackson是當前用的比較廣泛的,用來序列化和反序列化json的Java開源框架。Jackson社區(qū)相對比較活躍,更新速度也比較快,?從Github中的統(tǒng)計來看,Jackson是最流行的json解析器之一,Spring?MVC的默認json解析器便是Jackson。
Jackson優(yōu)點很多:
Jackson 所依賴的jar包較少,簡單易用。
與其他 Java 的 json 的框架 Gson 等相比,Jackson 解析大的 json 文件速度比較快。
Jackson 運行時占用內(nèi)存比較低,性能比較好
Jackson 有靈活的 API,可以很容易進行擴展和定制。
目前最新版本是2.9.4,Jackson 的核心模塊由三部分組成:
jackson-core 核心包,提供基于”流模式”解析的相關(guān) API,它包括 JsonPaser 和 JsonGenerator。Jackson 內(nèi)部實現(xiàn)正是通過高性能的流模式 API 的 JsonGenerator 和 JsonParser 來生成和解析 json。
jackson-annotations 注解包,提供標準注解功能;
jackson-databind 數(shù)據(jù)綁定包,提供基于”對象綁定”?解析的相關(guān) API( ObjectMapper )和”樹模型”?解析的相關(guān) API(JsonNode);基于”對象綁定”?解析的 API 和”樹模型”解析的 API 依賴基于”流模式”解析的 API。
為什么Jackson的介紹這么長啊?因為它也是本人的最愛。
Json-lib
項目地址:http://json-lib.sourceforge.net/index.html
json-lib最開始的也是應(yīng)用最廣泛的json解析工具,json-lib 不好的地方確實是依賴于很多第三方包,對于復雜類型的轉(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)化的需求。
編寫性能測試
接下來開始編寫這四個庫的性能測試代碼。
添加maven依賴
當然首先是添加四個庫的maven依賴,公平起見,我全部使用它們最新的版本:
<dependency>
????<groupId>net.sf.json-libgroupId>
????<artifactId>json-libartifactId>
????<version>2.4version>
????<classifier>jdk15classifier>
dependency>
<dependency>
????<groupId>com.google.code.gsongroupId>
????<artifactId>gsonartifactId>
????<version>2.8.2version>
dependency>
<dependency>
????<groupId>com.alibabagroupId>
????<artifactId>fastjsonartifactId>
????<version>1.2.46version>
dependency>
<dependency>
????<groupId>com.fasterxml.jackson.coregroupId>
????<artifactId>jackson-databindartifactId>
????<version>2.9.4version>
dependency>
<dependency>
????<groupId>com.fasterxml.jackson.coregroupId>
????<artifactId>jackson-annotationsartifactId>
????<version>2.9.4version>
dependency>
四個庫的工具類
FastJsonUtil.java
public?class?FastJsonUtil?{????public?static?String?bean2Json(Object?obj)?{
????????return?JSON.toJSONString(obj);
????}
????public?static??T?json2Bean(String?jsonStr,?Class?objClass)?{return?JSON.parseObject(jsonStr,?objClass);
????}
}
GsonUtil.java
public?class?GsonUtil?{????private?static?Gson?gson?=?new?GsonBuilder().create();
????public?static?String?bean2Json(Object?obj)?{
????????return?gson.toJson(obj);
????}
????public?static??T?json2Bean(String?jsonStr,?Class?objClass)?{return?gson.fromJson(jsonStr,?objClass);
????}public?static?String?jsonFormatter(String?uglyJsonStr)?{
????????Gson?gson?=?new?GsonBuilder().setPrettyPrinting().create();
????????JsonParser?jp?=?new?JsonParser();
????????JsonElement?je?=?jp.parse(uglyJsonStr);return?gson.toJson(je);
????}
}
JacksonUtil.java
public?class?JacksonUtil?{????private?static?ObjectMapper?mapper?=?new?ObjectMapper();
????public?static?String?bean2Json(Object?obj)?{
????????try?{
????????????return?mapper.writeValueAsString(obj);
????????}?catch?(JsonProcessingException?e)?{
????????????e.printStackTrace();
????????????return?null;
????????}
????}
????public?static??T?json2Bean(String?jsonStr,?Class?objClass)?{try?{return?mapper.readValue(jsonStr,?objClass);
????????}?catch?(IOException?e)?{
????????????e.printStackTrace();return?null;
????????}
????}
}
JsonLibUtil.java
public?class?JsonLibUtil?{????public?static?String?bean2Json(Object?obj)?{
????????JSONObject?jsonObject?=?JSONObject.fromObject(obj);
????????return?jsonObject.toString();
????}
????@SuppressWarnings("unchecked")
????public?static??T?json2Bean(String?jsonStr,?Class?objClass)?{return?(T)?JSONObject.toBean(JSONObject.fromObject(jsonStr),?objClass);
????}
}
準備Model類
這里我寫一個簡單的Person類,同時屬性有Date、List、Map和自定義的類FullName,最大程度模擬真實場景。
public?class?Person?{????private?String?name;
????private?FullName?fullName;
????private?int?age;
????private?Date?birthday;
????private?List?hobbies;private?Map?clothes;private?List?friends;//?getter/setter省略@Overridepublic?String?toString()?{
????????StringBuilder?str?=?new?StringBuilder("Person?[name="?+?name?+?",?fullName="?+?fullName?+?",?age="
????????????????+?age?+?",?birthday="?+?birthday?+?",?hobbies="?+?hobbies
????????????????+?",?clothes="?+?clothes?+?"]\n");if?(friends?!=?null)?{
????????????str.append("Friends:\n");for?(Person?f?:?friends)?{
????????????????str.append("\t").append(f);
????????????}
????????}return?str.toString();
????}
}public?class?FullName?{
????private?String?firstName;
????private?String?middleName;
????private?String?lastName;
????public?FullName()?{
????}
????public?FullName(String?firstName,?String?middleName,?String?lastName)?{
????????this.firstName?=?firstName;
????????this.middleName?=?middleName;
????????this.lastName?=?lastName;
????}
????//?省略getter和setter
????@Override
????public?String?toString()?{
????????return?"[firstName="?+?firstName?+?",?middleName="
????????????????+?middleName?+?",?lastName="?+?lastName?+?"]";
????}
}
JSON序列化性能基準測試
@BenchmarkMode(Mode.SingleShotTime)@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public?class?JsonSerializeBenchmark?{
????/**
?????*?序列化次數(shù)參數(shù)
?????*/
????@Param({"1000",?"10000",?"100000"})
????private?int?count;
????private?Person?p;
????public?static?void?main(String[]?args)?throws?Exception?{
????????Options?opt?=?new?OptionsBuilder()
????????????????.include(JsonSerializeBenchmark.class.getSimpleName())
????????????????.forks(1)
????????????????.warmupIterations(0)
????????????????.build();
????????Collection?results?=??new?Runner(opt).run();
????????ResultExporter.exportResult("JSON序列化性能",?results,?"count",?"秒");
????}@Benchmarkpublic?void?JsonLib()?{for?(int?i?=?0;?i?????????????JsonLibUtil.bean2Json(p);
????????}
????}@Benchmarkpublic?void?Gson()?{for?(int?i?=?0;?i?????????????GsonUtil.bean2Json(p);
????????}
????}@Benchmarkpublic?void?FastJson()?{for?(int?i?=?0;?i?????????????FastJsonUtil.bean2Json(p);
????????}
????}@Benchmarkpublic?void?Jackson()?{for?(int?i?=?0;?i?????????????JacksonUtil.bean2Json(p);
????????}
????}@Setuppublic?void?prepare()?{
????????List?friends=new?ArrayList();
????????friends.add(createAPerson("小明",null));
????????friends.add(createAPerson("Tony",null));
????????friends.add(createAPerson("陳小二",null));
????????p=createAPerson("邵同學",friends);
????}@TearDownpublic?void?shutdown()?{
????}private?Person?createAPerson(String?name,List?friends)?{
????????Person?newPerson=new?Person();
????????newPerson.setName(name);
????????newPerson.setFullName(new?FullName("zjj_first",?"zjj_middle",?"zjj_last"));
????????newPerson.setAge(24);
????????List?hobbies=new?ArrayList();
????????hobbies.add("籃球");
????????hobbies.add("游泳");
????????hobbies.add("coding");
????????newPerson.setHobbies(hobbies);
????????Map?clothes=new?HashMap();
????????clothes.put("coat",?"Nike");
????????clothes.put("trousers",?"adidas");
????????clothes.put("shoes",?"安踏");
????????newPerson.setClothes(clothes);
????????newPerson.setFriends(friends);return?newPerson;
????}
}
說明一下,上面的代碼中
ResultExporter.exportResult("JSON序列化性能",?results,?"count",?"秒");這個是我自己編寫的將性能測試報告數(shù)據(jù)填充至Echarts圖,然后導出png圖片的方法。
執(zhí)行后的結(jié)果圖:
從上面的測試結(jié)果可以看出,序列化次數(shù)比較小的時候,Gson性能最好,當不斷增加的時候到了100000,Gson明細弱于Jackson和FastJson,?這時候FastJson性能是真的牛,另外還可以看到不管數(shù)量少還是多,Jackson一直表現(xiàn)優(yōu)異。而那個Json-lib簡直就是來搞笑的。^_^
JSON反序列化性能基準測試
@BenchmarkMode(Mode.SingleShotTime)@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public?class?JsonDeserializeBenchmark?{
????/**
?????*?反序列化次數(shù)參數(shù)
?????*/
????@Param({"1000",?"10000",?"100000"})
????private?int?count;
????private?String?jsonStr;
????public?static?void?main(String[]?args)?throws?Exception?{
????????Options?opt?=?new?OptionsBuilder()
????????????????.include(JsonDeserializeBenchmark.class.getSimpleName())
????????????????.forks(1)
????????????????.warmupIterations(0)
????????????????.build();
????????Collection?results?=??new?Runner(opt).run();
????????ResultExporter.exportResult("JSON反序列化性能",?results,?"count",?"秒");
????}
????@Benchmarkpublic?void?JsonLib()?{for?(int?i?=?0;?i?????????????JsonLibUtil.json2Bean(jsonStr,?Person.class);
????????}
????}
????@Benchmarkpublic?void?Gson()?{for?(int?i?=?0;?i?????????????GsonUtil.json2Bean(jsonStr,?Person.class);
????????}
????}
????@Benchmarkpublic?void?FastJson()?{for?(int?i?=?0;?i?????????????FastJsonUtil.json2Bean(jsonStr,?Person.class);
????????}
????}
????@Benchmarkpublic?void?Jackson()?{for?(int?i?=?0;?i?????????????JacksonUtil.json2Bean(jsonStr,?Person.class);
????????}
????}
????@Setuppublic?void?prepare()?{
????????jsonStr="{\"name\":\"邵同學\",\"fullName\":{\"firstName\":\"zjj_first\",\"middleName\":\"zjj_middle\",\"lastName\":\"zjj_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"籃球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":[{\"name\":\"小明\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"籃球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null},{\"name\":\"Tony\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"籃球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null},{\"name\":\"陳小二\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"籃球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null}]}";
????}
????@TearDownpublic?void?shutdown()?{
????}
}
執(zhí)行后的結(jié)果圖:
從上面的測試結(jié)果可以看出,反序列化的時候,Gson、Jackson和FastJson區(qū)別不大,性能都很優(yōu)異,而那個Json-lib還是來繼續(xù)搞笑的。
< END >
2019年互聯(lián)網(wǎng)公司月餅顏值大比拼!全網(wǎng)最硬核換臉技術(shù)全分析ZAO換臉App徹底掌握Git操作,從入門到高手開號以來最牛的資源分享,打包送給你2019最新Vue開發(fā)指南,值得收藏!長按加入10W+朋友的IT圈
↓↓↓?戳?“閱讀原文”?,第四期打卡活動詳情!
總結(jié)
以上是生活随笔為你收集整理的gson解析天气json_几种常用JSON解析库性能比较的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vbs修改office设置_E002 R
- 下一篇: springboot不会运行gc_Spr