Comparison of various JSON technologies (Jackson, Gson, Fastjson)

1. Introduction and advantages and disadvantages of each JSON technology

1.json-lib

The beginning of json-lib is also the most widely used json parsing tool. The disadvantage of json-lib is that it depends on many third-party packages,
including commons-beanutils.jar, commons-collections-3.2.jar, commons-lang- 2.6.jar, commons-logging-1.1.1.jar, ezmorph-1.0.6.jar,
for complex type conversion, json-lib has defects for converting json to bean, for example, one class will appear in another class list or map collection, json-lib will have problems converting from json to bean.
json-lib cannot meet the needs of the current Internet in terms of function and performance.

 

2. Open Source Jackson

Compared with the json-lib framework, Jackson relies on fewer jar packages, is easy to use and has relatively high performance.
Moreover, the Jackson community is relatively active, and the update speed is relatively fast.
Jackson will have problems with json conversion beans of complex types, and some collection Map and List conversion will have problems.
Jackson converts Json for complex types of beans, and the converted json format is not the standard Json format

 

3. Google’s Gson

Gson is currently the most fully functional Json parsing artifact. Gson was originally developed by Google in response to Google's internal needs,
but since the first version was publicly released in May 2008, it has been used by many companies or users.
The application of Gson mainly consists of two conversion functions, toJson and fromJson, which have no dependencies, do not require additional jars with exceptions, and can run directly on the JDK.
Before using this object conversion, you need to create the type of the object and its members to successfully convert the JSON string into the corresponding object.
As long as there are get and set methods in the class, Gson can completely convert complex types of json to bean or bean to json. It is an artifact of JSON parsing.
Gson is impeccable in function, but there is a gap in performance compared to FastJson.

 

4. Alibaba's FastJson

Fastjson is a high-performance JSON processor written in Java language, developed by Alibaba.
No dependencies, no extra jars are required, and it can run directly on the JDK.
FastJson will have some problems in Bean conversion Json of complex types, there may be reference types, resulting in errors in Json conversion, and references need to be formulated.
FastJson uses an original algorithm to increase the speed of parse to the extreme, surpassing all json libraries.

 

To sum up the comparison of the four Json technologies, Google's Gson and Alibaba's FastJson can be used in parallel during project selection.
If only functional requirements are required, but no performance requirements, Google's Gson can be used.
If there are performance requirements It is required that Gson can be used to convert bean to json to ensure the correctness of the data, and FastJson is used to convert Json to bean

 

 

 

2. Introduction to the use of Google's Gson package.

Gson class: the most basic tool class for parsing json
JsonParser class: parser to parse JSON to JsonElements parse tree
JsonElement class: a class representing JSON elements
JsonObject class: JSON object type
JsonArray class: JsonObject array
TypeToken class: used to create type, such as the generic List<?>

 

 

(1) maven dependency
com.google.code.gson
gson
2.2.4

(2) Basic conversion class
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(intage) {
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 conversion json
Gson gson = new Gson();
String json = gson.toJson(obj);
obj is the object
(4) json conversion bean
Gson gson = new Gson();
String json = "{\"id\":\"2\",\"name\":\"Json技术\"}";
Book book = gson.fromJson(json, Book.class);
(5) json converts complex beans, such as List, Set
Convert json to complex type bean, need to use TypeToken
Gson gson = new Gson();
String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]";
//Convert json to List
List list = gson.fromJson(json,new TypeToken<LIST>() {}.getType());
//Convert json to Set
Set set = gson.fromJson(json,new TypeToken<SET>() {}.getType());
(6) Directly manipulate json and some json tools through json objects
a) Format Json
String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]";
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement i = jp.parse(json);
json = gson.toJson (is);
b) Determine whether the string is json, and judge whether it is json by the caught exception
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) get properties from json string
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) remove an attribute in 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) add properties to json
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
String propertyName = 'desc';
Object propertyValue = "Research on various technologies of 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) Modify the properties in json
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
String propertyName = 'name';
Object propertyValue = "Research on various technologies of 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) Determine whether there is an attribute in 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) Handling of date formats in json
GsonBuilder builder = new GsonBuilder();
builder.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Gson gson = builder.create();
Then use the gson object for json processing. If there is an object of the Date class, it will be processed according to the set format.
i) Escape for Html in json
Gson gson = new Gson();
This object escapes Html by default. If you don't want to escape, use the following method
GsonBuilder builder = new GsonBuilder();
builder.disableHtmlEscaping();
Gson gson = builder.create();

 

 

3. Introduction to the use of Alibaba's FastJson package.

(1) maven dependency

com.alibaba
fastjson
1.1.22

(2) Basic conversion class
Ditto
(3) bean conversion json
Convert object to formatted json
JSON.toJSONString(obj,true);
Convert object to unformatted json
JSON.toJSONString(obj,false);
obj design object
For the conversion of complex types, the quoted characters appear in the json string after the repeated reference is converted into a json string, such as $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 conversion bean
String json = "{\"id\":\"2\",\"name\":\"Json技术\"}";
Book book = JSON.parseObject(json, Book.class);
(5) json converts complex beans, such as List, Map
String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]";
//Convert json to List
List list = JSON.parseObject(json,new TypeReference<ARRAYLIST>(){});
//Convert json to Set
Set set = JSON.parseObject(json,new TypeReference<HASHSET>(){});
(6) Directly manipulate json through json object
a) get properties from json string
String propertyName = 'id';
String propertyValue = "";
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
JSONObject obj = JSON.parseObject(json);
propertyValue = obj.get(propertyName));
b) remove an attribute in 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) add properties to json
String propertyName = 'desc';
Object propertyValue = "json stuff";
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
JSONObject obj = JSON.parseObject(json);
obj.put(propertyName, JSON.toJSONString(propertyValue));
json = obj.toString();
d) Modify the properties in json
String propertyName = 'name';
Object propertyValue = "json stuff";
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) Determine whether there is an attribute in 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) Processing of date format in json
Object obj = new Date();
String json = JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss.SSS");
Use JSON.toJSONStringWithDateFormat, this method can use the set date format to convert the date

 

 

3. Introduction to the use of the json-lib package.

 

(1) maven dependency

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) Basic conversion class
Ditto
(3) bean conversion json
a) Convert the class to Json, obj is a normal object, not a List, Map object
String json = JSONObject.fromObject(obj).toString();
b) Convert List, Map to Json
String json = JSONArray.fromObject(list).toString();
String json = JSONArray.fromObject(map).toString();
(4) json conversion bean
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
JSONObject jsonObj = JSONObject.fromObject(json);
Book book = (Book)JSONObject.toBean(jsonObj,Book.class);
(5) json converts List, there will be problems with the conversion of complex types
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 conversion 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) The operation of json for dates is more complicated and requires the use of JsonConfig, which is more troublesome than Gson and FastJson
Create a converted interface implementation class to convert to a date in a specified format
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 for json operation and processing
a) get properties from json string
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) remove an attribute in 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) Add and modify attributes to json, modify if there is, add if not
String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}";
Object key = "desc";
Object value = "Good stuff for json";
JSONObject jsonObject = JSONObject.fromObject(jsonString);
jsonObject.put(key,value);
jsonString = jsonObject.toString();
d) Determine whether there is an attribute in json
String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}";
boolean containFlag = false;
Object key = "desc";
JSONObject jsonObject = JSONObject.fromObject(jsonString);
containFlag = jsonObject.containsKey(key);

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326156380&siteId=291194637