天天看點

4種json解析技術對比

JSON技術的調研報告

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

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-lib在功能和性能上面都不能滿足現在網際網路化的需求。

2.開源的Jackson

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

而且Jackson社群相對比較活躍,更新速度也比較快。

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

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

三、阿裡巴巴的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,該方法可以使用設定的日期格式對日期進行轉換

三、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);

文章出自:http://www.cnblogs.com/kunpengit/p/4001680.html