Jackson Gson Json.simple 比較

爲公司作了小任務,須要用到Java Json庫,Json庫我幾個月以前就用過,不過那時候是跟着項目來的,延續了項目的使用習慣直接用了jackson Json,而此次我以爲好比如較一下幾個常見的Json庫,而後選一個最快的。json

 

看了幾篇blog,以爲其實可選的就三種,jackson, gson, json.simple。我最初用了json.simple,而後寫出來了這樣的函數函數

從URL中讀取Json數據,而且在Request中添加身份信息google

    public static JSONObject readJsonFromUrl(String url, String token) {
        try { URLConnection conn = new URL(url).openConnection(); conn.setRequestProperty("Authorization", "Bearer " + token); InputStream response = conn.getInputStream(); String JsonStr = IOUtils.toString(response); JSONObject jsonObj = (JSONObject)JSONValue.parseWithException(JsonStr); // System.out.println(jsonObj); return jsonObj; }catch (Exception e) { e.printStackTrace(); } return null; }

而後,抽取Json中的數據url

    public static Reply parseJson(JSONObject jsonObj) {
        Reply reply = new Reply(jsonObj.get("next_stream_position").toString()); JSONArray jsonAry = (JSONArray)(jsonObj.get("entries")); for(int i = 0; i < jsonAry.size(); i ++) { JSONObject iObj = (JSONObject)jsonAry.get(i); reply.addIPAddr(iObj.get("ip_address").toString()); } return reply; }

 

寫完以後,我以爲有必要將Json替換成更加高效的實現,因而我打算從Jackson, Gson中挑一種使用spa

Jackson適合處理大量的數據,Gson適合處理小些的數據,而且Gson的jar包比其餘選擇小了不少,給我一種很輕巧的感受。code

此外,我很不情願爲Json數據寫一個POJO,由於我只要這個POJO中的一兩個成員變量。Jackson不只要這個POJO,還須要在這個POJO上加上annotation,因此我直接把它排除了。blog

Gson,google的產品,給我一種能夠信賴的感受。因而我寫出了這樣的代碼token

    public static Reply readJsonFromUrl(String url, String token) {
        Reply reply = new Reply(); try { URLConnection conn = new URL(url).openConnection(); conn.setRequestProperty("Authorization", "Bearer " + token); InputStream response = conn.getInputStream(); JsonReader reader = new JsonReader(new InputStreamReader(response, "UTF-8")); // only one element will be returned // parse data recursively // google's way to handle streaming data, ugly though  reader.beginObject(); reader.beginObject(); while(reader.hasNext()) { String name = reader.nextName(); if(name.equals("next_stream_position")) reply.stream_position = reader.nextString(); else if(name.equals("entries")) { reader.beginArray(); while(reader.hasNext()) { reader.beginObject(); while(reader.hasNext()) { name = reader.nextName(); if(name.equals("ip_address")) reply.addIPAddr(reader.nextString()); else if(name.equals("created_at")) reply.lastDate = reader.nextString(); else reader.skipValue(); } reader.endObject(); } reader.endArray(); } else reader.skipValue(); } reader.endObject(); reader.close(); return reply; }catch (Exception e) { e.printStackTrace(); } return null; }

因爲須要處理流式數據且不肯意寫POJO,最終就寫成了上面這一坨醜陋不堪的代碼,我想這下效率卻是能夠保證了。ip

 

寫完代碼後我想了下,以爲最合適的Json庫應該仍是Json.simple,它的轉換簡單,能夠直接根據String get到想要的那一個信息,且最重要的是代碼寫的短,實現的效率高。在企業,在學校,在面臨交差的任何地方,用最短的時間完成任務纔是最重要的,這一點我已深有體會。element

 

Well,之後默認用Json.simple

相關文章
相關標籤/搜索