【Java】各個JSON技術的比較

一 、各個JSON技術的簡介和優劣java

1. json-lib算法

json-lib最開始的也是應用最普遍的json解析工具,json-lib 很差的地方確實是依賴於不少第三方包,包括commons-beanutils.jar,commons-collections-3.2.jar,commons-lang-2.6.jar,commons-logging-1.1.1.jar,ezmorph-1.0.6.jar,對於複雜類型的轉換,json-lib對於json轉換成bean還有缺陷,好比一個類裏面會出現另外一個類的list或者map集合,json-lib從json到bean的轉換就會出現問題。json

json-lib在功能和性能上面都不能知足如今互聯網化的需求。api

2. 開源的Jackson數組

相比json-lib框架,Jackson所依賴的jar包較少,簡單易用而且性能也要相對高些。框架

並且Jackson社區相對比較活躍,更新速度也比較快。maven

Jackson對於複雜類型的json轉換bean會出現問題,一些集合Map,List的轉換出現問題。函數

Jackson對於複雜類型的bean轉換Json,轉換的json格式不是標準的Json格式工具

3. Google的Gson性能

Gson是目前功能最全的Json解析神器,Gson當初是爲因應Google公司內部需求而由Google自行研發而來,
但自從在2008年五月公開發布初版後已被許多公司或用戶應用。

Gson的應用主要爲toJson與fromJson兩個轉換函數,無依賴,不須要例外額外的jar,可以直接跑在JDK上。

而在使用這種對象轉換以前需先建立好對象的類型以及其成員才能成功的將JSON字符串成功轉換成相對應的對象。

類裏面只要有get和set方法,Gson徹底能夠將複雜類型的json到bean或bean到json的轉換,是JSON解析的神器。

Gson在功能上面無可挑剔,可是性能上面比FastJson有所差距。

4.阿里巴巴的FastJson

Fastjson是一個Java語言編寫的高性能的JSON處理器,由阿里巴巴公司開發。

無依賴,不須要例外額外的jar,可以直接跑在JDK上。

FastJson在複雜類型的Bean轉換Json上會出現一些問題,可能會出現引用的類型,致使Json轉換出錯,須要制定引用。

FastJson採用首創的算法,將parse的速度提高到極致,超過全部json庫。

 

綜上4種Json技術的比較,在項目選型的時候可使用Google的Gson和阿里巴巴的FastJson兩種並行使用,若是隻是功能要求,沒有性能要求,可使用google的Gson,若是有性能上面的要求可使用Gson將bean轉換json確保數據的正確,使用FastJson將Json轉換Bean。

 

2、Google的Gson包的使用簡介

Gson類:解析json的最基礎的工具類
JsonParser類:解析器來解析JSON到JsonElements的解析樹
JsonElement類:一個類表明的JSON元素
JsonObject類:JSON對象類型
JsonArray類:JsonObject數組
TypeToken類:用於建立type,好比泛型List<?>

 

(1)maven依賴

com.google.code.gson

gson

2.2.4

(2)基礎轉換類

public class Book{

    private String id;

    private String name;

    public Book() {

        super();

    }

    public String getId() {

        return id;

    }

    public void setId(String id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

}

public class Student{

    private String name;

    private int age;

    private String sex;

    private String describe;

    private Set books;

    public Student() {

        super();

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public int getAge() {

        return age;

    }

    public void setAge(int age) {

        this.age = age;

    }

    public String getSex() {

        return sex;

    }

    public void setSex(String sex) {

        this.sex = sex;

    }

    public Set getBooks() {

        return books;

    }

    public void setBooks(Set books) {

        this.books = books;

    }

    public String getDescribe() {

        return describe;

    }

    public void setDescribe(String describe) {

        this.describe = describe;

    }

}

(3) bean轉換json

Gson gson = new Gson();

String json = gson.toJson(obj);  //obj是對象

(4)json轉換bean

Gson gson = new Gson();

String json = "{\"id\":\"2\",\"name\":\"Json技術\"}";

Book book = gson.fromJson(json, Book.class);

(5)json轉換複雜的bean,好比List,Set

將json轉換成複雜類型的bean,須要使用TypeToken

Gson gson = new Gson();

String json = "[{\"id\":\"1\",\"name\":\"Json技術\"},{\"id\":\"2\",\"name\":\"java技術\"}]";

//將json轉換成List

List list = gson.fromJson(json,new TypeToken<LIST>() {}.getType());

//將json轉換成Set

Set set = gson.fromJson(json,new TypeToken<SET>() {}.getType());

(6) 經過json對象直接操做json以及一些json的工具

a)格式化Json

String json = "[{\"id\":\"1\",\"name\":\"Json技術\"},{\"id\":\"2\",\"name\":\"java技術\"}]";

Gson gson = new GsonBuilder().setPrettyPrinting().create();

JsonParser jp = new JsonParser();

JsonElement je = jp.parse(json);

json = gson.toJson(je);

b)判斷字符串是不是json,經過捕捉的異常來判斷是不是json

String json = "[{\"id\":\"1\",\"name\":\"Json技術\"},{\"id\":\"2\",\"name\":\"java技術\"}]";

boolean jsonFlag;

try {

new JsonParser().parse(str).getAsJsonObject();

jsonFlag = true;

} catch (Exception e) {

jsonFlag = false;

}

c)從json串中獲取屬性

String json = "{\"id\":\"1\",\"name\":\"Json技術\"}";

String propertyName = 'id';

String propertyValue = "";

try {

JsonParser jsonParser = new JsonParser();

JsonElement element = jsonParser.parse(json);

JsonObject jsonObj = element.getAsJsonObject();

propertyValue = jsonObj.get(propertyName).toString();

} catch (Exception e) {

propertyValue = null;

}

d)除去json中的某個屬性

String json = "{\"id\":\"1\",\"name\":\"Json技術\"}";

String propertyName = 'id';

JsonParser jsonParser = new JsonParser();

JsonElement element = jsonParser.parse(json);

JsonObject jsonObj = element.getAsJsonObject();

jsonObj.remove(propertyName);

json = jsonObj.toString();

e)向json中添加屬性

String json = "{\"id\":\"1\",\"name\":\"Json技術\"}";

String propertyName = 'desc';

Object propertyValue = "json各類技術的調研";

JsonParser jsonParser = new JsonParser();

JsonElement element = jsonParser.parse(json);

JsonObject jsonObj = element.getAsJsonObject();

jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue));

json = jsonObj.toString();

f)修改json中的屬性

String json = "{\"id\":\"1\",\"name\":\"Json技術\"}";

String propertyName = 'name';

Object propertyValue = "json各類技術的調研";

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();

g)判斷json中是否有屬性

String json = "{\"id\":\"1\",\"name\":\"Json技術\"}";

String propertyName = 'name';

boolean isContains = false ;

JsonParser jsonParser = new JsonParser();

JsonElement element = jsonParser.parse(json);

JsonObject jsonObj = element.getAsJsonObject();

isContains = jsonObj.has(propertyName);

h)json中日期格式的處理

GsonBuilder builder = new GsonBuilder();

builder.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

Gson gson = builder.create();

而後使用gson對象進行json的處理,若是出現日期Date類的對象,就會按照設置的格式進行處理

i)json中對於Html的轉義

Gson gson = new Gson();

這種對象默認對Html進行轉義,若是不想轉義使用下面的方法

GsonBuilder builder = new GsonBuilder();

builder.disableHtmlEscaping();

Gson gson = builder.create();

 

3、阿里巴巴的FastJson包的使用簡介

(1)maven依賴

com.alibaba

fastjson

1.1.22

(2)基礎轉換類

同上

(3)bean轉換json

將對象轉換成格式化的json

JSON.toJSONString(obj,true);

將對象轉換成非格式化的json

JSON.toJSONString(obj,false);

obj設計對象

對於複雜類型的轉換,對於重複的引用在轉成json串後在json串中出現引用的字符,好比 $ref":"$[0].books[1]

Student stu = new Student();

Set books= new HashSet();

Book book = new Book();

books.add(book);

stu.setBooks(books);

List list = new ArrayList();

for(int i=0;i<5;i++)

list.add(stu);

String json = JSON.toJSONString(list,true);

(4)json轉換bean

String json = "{\"id\":\"2\",\"name\":\"Json技術\"}";

Book book = JSON.parseObject(json, Book.class);

(5)json轉換複雜的bean,好比List,Map

String json = "[{\"id\":\"1\",\"name\":\"Json技術\"},{\"id\":\"2\",\"name\":\"java技術\"}]";

//將json轉換成List

List list = JSON.parseObject(json,new TypeReference<ARRAYLIST>(){});

//將json轉換成Set

Set set = JSON.parseObject(json,new TypeReference<HASHSET>(){});

(6)經過json對象直接操做json

a)從json串中獲取屬性

String propertyName = 'id';

String propertyValue = "";

String json = "{\"id\":\"1\",\"name\":\"Json技術\"}";

JSONObject obj = JSON.parseObject(json);

propertyValue = obj.get(propertyName));

b)除去json中的某個屬性

String propertyName = 'id';

String propertyValue = "";

String json = "{\"id\":\"1\",\"name\":\"Json技術\"}";

JSONObject obj = JSON.parseObject(json);

Set set = obj.keySet();

propertyValue = set.remove(propertyName);

json = obj.toString();

c)向json中添加屬性

String propertyName = 'desc';

Object propertyValue = "json的玩意兒";

String json = "{\"id\":\"1\",\"name\":\"Json技術\"}";

JSONObject obj = JSON.parseObject(json);

obj.put(propertyName, JSON.toJSONString(propertyValue));

json = obj.toString();

d)修改json中的屬性

String propertyName = 'name';

Object propertyValue = "json的玩意兒";

String json = "{\"id\":\"1\",\"name\":\"Json技術\"}";

JSONObject obj = JSON.parseObject(json);

Set set = obj.keySet();

if(set.contains(propertyName))

obj.put(propertyName, JSON.toJSONString(propertyValue));

json = obj.toString();

e)判斷json中是否有屬性

String propertyName = 'name';

boolean isContain = false;

String json = "{\"id\":\"1\",\"name\":\"Json技術\"}";

JSONObject obj = JSON.parseObject(json);

Set set = obj.keySet();

isContain = set.contains(propertyName);

f)json中日期格式的處理

Object obj = new Date();

String json = JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss.SSS");

使用JSON.toJSONStringWithDateFormat,該方法可使用設置的日期格式對日期進行轉換

 

4、json-lib包的使用簡介

(1)maven依賴

net.sf.json-lib

json-lib

jdk15

2.2.2

 

commons-beanutils

commons-beanutils

1.8.3

 

commons-collections

commons-collections

3.2

 

commons-lang

commons-lang

2.6

 

commons-logging

commons-logging

1.1.1

 

net.sf.ezmorph

ezmorph

1.0.6

(2)基礎轉換類

同上

(3) bean轉換json

a)將類轉換成Json,obj是普通的對象,不是List,Map的對象

String json = JSONObject.fromObject(obj).toString();

b)將List,Map轉換成Json

String json = JSONArray.fromObject(list).toString();

String json = JSONArray.fromObject(map).toString();

(4) json轉換bean

String json = "{\"id\":\"1\",\"name\":\"Json技術\"}";

JSONObject jsonObj = JSONObject.fromObject(json);

Book book = (Book)JSONObject.toBean(jsonObj,Book.class);

(5) json轉換List,對於複雜類型的轉換會出現問題

String json = "[{\"id\":\"1\",\"name\":\"Json技術\"},{\"id\":\"2\",\"name\":\"Java技術\"}]";

JSONArray jsonArray = JSONArray.fromObject(json);

JSONObject jsonObject;

T bean;

int size = jsonArray.size();

List list = new ArrayList(size);

for (int i = 0; i < size; i++) {

jsonObject = jsonArray.getJSONObject(i);

bean = (T) JSONObject.toBean(jsonObject, beanClass);

list.add(bean);

}

(6) json轉換Map

String jsonString = "{\"id\":\"1\",\"name\":\"Json技術\"}";

JSONObject jsonObject = JSONObject.fromObject(jsonString);

Iterator keyIter = jsonObject.keys();

String key;

Object value;

Map valueMap = new HashMap();

while (keyIter.hasNext()) {

key = (String) keyIter.next();

value = jsonObject.get(key).toString();

valueMap.put(key, value);

}

(7) json對於日期的操做比較複雜,須要使用JsonConfig,比Gson和FastJson要麻煩多了建立轉換的接口實現類,轉換成指定格式的日期

class DateJsonValueProcessor implements JsonValueProcessor{

    public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS";

    private DateFormat dateFormat;

    public DateJsonValueProcessor(String datePattern) {

        try {

            dateFormat = new SimpleDateFormat(datePattern);

        } catch (Exception ex) {

            dateFormat = new SimpleDateFormat(DEFAULT_DATE_PATTERN);

        }

    }

    public Object processArrayValue(Object value, JsonConfig jsonConfig) {

        return process(value);

    }

    public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {

        return process(value);

    }

    private Object process(Object value) {

        return dateFormat.format[1];

        Map<STRING,DATE> birthDays = new HashMap<STRING,DATE>();

        birthDays.put("WolfKing",new Date());

        JSONObject jsonObject = JSONObject.fromObject(birthDays, jsonConfig);

        String json = jsonObject.toString();

        System.out.println(json);

    }

}

(8) JsonObject 對於json的操做和處理

a)從json串中獲取屬性

String jsonString = "{\"id\":\"1\",\"name\":\"Json技術\"}";

Object key = "name";

Object value = null;

JSONObject jsonObject = JSONObject.fromObject(jsonString);

value = jsonObject.get(key);

jsonString = jsonObject.toString();

b)除去json中的某個屬性

String jsonString = "{\"id\":\"1\",\"name\":\"Json技術\"}";

Object key = "name";

Object value = null;

JSONObject jsonObject = JSONObject.fromObject(jsonString);

value = jsonObject.remove(key);

jsonString = jsonObject.toString();

c)向json中添加和修改屬性,有則修改,無則添加

String jsonString = "{\"id\":\"1\",\"name\":\"Json技術\"}";

Object key = "desc";

Object value = "json的好東西";

JSONObject jsonObject = JSONObject.fromObject(jsonString);

jsonObject.put(key,value);

jsonString = jsonObject.toString();

d)判斷json中是否有屬性

String jsonString = "{\"id\":\"1\",\"name\":\"Json技術\"}";

boolean containFlag = false;

Object key = "desc";

JSONObject jsonObject = JSONObject.fromObject(jsonString);

containFlag = jsonObject.containsKey(key);

相關文章
相關標籤/搜索