[Android development experience] 10 times faster than Gson parsing! -- Introduction to The Json parser Jackson, gsonjson

Source: Internet
Author: User

[Android development experience] 10 times faster than Gson parsing! -- Introduction to The Json parser Jackson, gsonjson

Reprinted please indicate the source: http://blog.csdn.net/zhaokaiqiang1992

In the previous two articles, we introduced the Json data format and the built-in Json and Google Gson projects. If you can learn these things, you can basically meet your work needs. However, programmers have the hobby of pursuing ultimate efficiency. After meeting the basic requirements, we will consider whether we can optimize the efficiency? Of course! This article introduces the Json data parsing framework, which is nearly 10 times more efficient than Gson in terms of data volume.-Jackson!

Below is a great God about several common Json data parsing speed test results, the original please stamp http://wangym.iteye.com/blog/738933


As we can see, in the case of large data volumes, Jackson is faster than Gson's resolution speed than half past one. Therefore, we recommend that you use the Jackson framework, let's take a look at how to use it!

Let's first introduce the features of several common classes:

JsonFactory: this class is the main factory method of the Jackson project. It is mainly used to configure and build a parser (such as JsonParser) and a generator (such as JsonGenerator). This factory instance is thread-safe, if any configuration is available, you can use it again.

JsonGenerator: this class is mainly used to generate content in Json format. We can use the JsonFactory method to generate an instance.

JsonParser: This is mainly used to read the content in Json format and complete the parsing operation. We can use the JsonFactory method to generate an instance.

ObjectMapper: This class provides conversion between a Java object and a Json object, mainly through the JsonParser and JsonGenerator instances to complete actual read/write operations on Json data. This class is a subclass of ObjectCodec. The main implementation details are in ObjectCodec. This class can be used repeatedly, so a singleton mode of this class is generally created, for example, the following code

Package com. example. jsondemo; import org. codehaus. jackson. map. objectMapper;/***** @ ClassName: com. example. jsondemo. jacksonMapper * @ Description: single-instance mode of ObjectMapper * @ author zhaokaiqiang * @ date 4:06:52 **/public class JacksonMapper {private static final ObjectMapper mapper = new ObjectMapper (); private JacksonMapper () {}public static ObjectMapper getInstance () {return mapper ;}}

In the following code, we often use this Singleton mode, so don't be confused.


1. Json data generation of Simple objects

The simple object mentioned here refers to a single object or a collection class of the object.

Next, let's take a look at the code implementation and explain some details.

There are two implementation methods. First, the first one is as follows:

public String getJsonString(Object object) throws Exception {return JacksonMapper.getInstance().writeValueAsString(object);}
In this method, we can directly use the writeValueAsString () of the ObjectMapper class to directly return the json format of the object as the return value.

In addition, we can also use the second method. The Code is as follows:

public String getJsonString1(Object object) throws Exception {ObjectMapper mapper = JacksonMapper.getInstance();StringWriter sw = new StringWriter();JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);mapper.writeValue(gen, object);gen.flush();gen.close();return sw.toString();}
This method uses JsonGenerator and StringWriter objects to write converted Json data to StringWriter through ObjectMapper, and then toString () can get the Json data we need.

Here we can say that from the second method, we can see that the operations are very similar to the IO stream processing in Java. In fact, jackson does process data in a stream, which is also the reason for its speed.

Because the first method is more concise, we recommend that you use it.

The following is the test code and result.

/*** Collection object ** @ throws Exception */public void objectsToJson () throws Exception {Person p = new Person ("zhaokaiqiang", 22, new Birthday (1992, 1, 19); ArrayList <Person> persons = new ArrayList <Person> (); persons. add (p); persons. add (p); persons. add (p); Log. d (TAG, getJsonString (persons);}/*** single object ** @ throws Exception */public void objectToJson () throws Exception {Person p = new Person ("zhaokaiqiang", 22, new Birthday (1992, 1, 19); Log. d (TAG, getJsonString (p ));}

The test results are as follows:

{"name":"zhaokaiqiang","birthday":{"day":19,"month":1,"year":1992},"age":22}
[{"name":"zhaokaiqiang","birthday":{"day":19,"month":1,"year":1992},"age":22},{"name":"zhaokaiqiang","birthday":{"day":19,"month":1,"year":1992},"age":22},{"name":"zhaokaiqiang","birthday":{"day":19,"month":1,"year":1992},"age":22}]


2. Json data generation of complex objects

The complex object mentioned here refers to the data composed of multiple different data types. The following describes how to create Json data for such complex objects.

As we have discussed earlier, the Json format is divided into the Object format and the Array format. We will introduce how to generate the two formats respectively.

(1) Object format

Let's look at the following code first!

/*** Generate json in Object format ** @ throws Exception */public void createObjectJson () throws Exception {Person p = new Person ("zhaokaiqiang", 22, new Birthday (1992, 1, 19); StringWriter stringWriter = new StringWriter (); // JsonGenerator jsonGenerator = JacksonMapper must be obtained in this way. getInstance (). getJsonFactory (). createJsonGenerator (stringWriter); jsonGenerator. writeStartObject (); jsonGenerator. writeStringField ("name", "zhaokaiqiang"); jsonGenerator. writeNumberField ("age", 22); jsonGenerator. writeObjectField ("person", p); jsonGenerator. writeEndObject (); jsonGenerator. flush (); jsonGenerator. close (); Log. d (TAG, stringWriter. toString ());}
JsonGenerator is a generator. To create a complex Json object, we can use this class. However, it must be noted that the method of obtaining JsonGenerator must be used. We must use getJsonFactory () of ObjectMapper and then create a JsonGenerator. Otherwise, if we use the writeObjectField () method, the following exception is reported.

Java. lang. IllegalStateException: No ObjectCodec defined for the generator, can only serialize simple wrapper types (type passed com. example. jsondemo. Person)

The rest of the above code is very simple. You only need to call the corresponding write ___ Field () based on different data types.

The test results are as follows:

{"name":"zhaokaiqiang","age":22,"person":{"name":"zhaokaiqiang","birthday":{"day":19,"month":1,"year":1992},"age":22}}

(2) Array format

The following describes how to generate Json data in Array format, which is similar to the preceding one.

The following is code implementation:

/*** Create json in Array format ** @ throws Exception */public void createArrayJson () throws Exception {Person p = new Person ("zhaokaiqiang", 22, new Birthday (1992, 1, 19); StringWriter stringWriter = new StringWriter (); // JsonGenerator jsonGenerator = JacksonMapper can only be obtained in this way. getInstance (). getJsonFactory (). createJsonGenerator (stringWriter); jsonGenerator. writeStartArray (); jsonGenerator. writeString ("zhaokaiqiang"); jsonGenerator. writeNumber (22); jsonGenerator. writeObject (p); jsonGenerator. writeEndArray (); jsonGenerator. flush (); jsonGenerator. close (); Log. d (TAG, stringWriter. toString ());}
The idea is the same. The following is the test result:
["zhaokaiqiang",22,{"name":"zhaokaiqiang","birthday":{"day":19,"month":1,"year":1992},"age":22}]

3. parse simple Json objects

The following describes how to parse Json data as a Java object.

Let's look at the parsing code directly.

public void toObject() throws Exception {ObjectMapper objectMapper = new ObjectMapper();Person p = new Person("zhaokaiqiang", 22, new Birthday(1992, 1, 19));String jsonString = getJsonString(p);Person person = objectMapper.readValue(jsonString, Person.class);Log.d(TAG, person.toString());}

During parsing, we still need to use the ObjectMapper object to call readValue, and then input the json data to be parsed and the class of the Conversion Type to complete the conversion.

Below is the code for parsing a simple set object

public void toObjects() throws Exception {Person p = new Person("zhaokaiqiang", 22, new Birthday(1992, 1, 19));ArrayList<Person> persons = new ArrayList<Person>();persons.add(p);persons.add(p);persons.add(p);ObjectMapper objectMapper = new ObjectMapper();String jsonString = getJsonString(persons);@SuppressWarnings("unchecked")ArrayList<Person> arrayList = objectMapper.readValue(jsonString,new ArrayList<Person>().getClass());Log.d(TAG, arrayList.toString());}


4. parse complex Json objects

The complex object mentioned here is equivalent to the complex Json object generated above. It refers to a Json object not of a simple basic type or a single object set. The parsing test text is in the following form:

{"name":"zhaokaiqiang","age":22,"person":{"name":"zhaokaiqiang","birthday":{"day":19,"month":1,"year":1992},"age":22}}
This string contains the string type, int type, and a custom object with object attributes. Therefore, the above method of Type reflection cannot be used for parsing, because this Object is complex, after research, I decided to use the segmentation method for parsing, that is, for the Json data of this Object type, the value is retrieved based on the key, then parse the user-defined objects separately. The Code is as follows:

public void fromJsons() throws Exception {String jsonString = createObjectJson();ObjectMapper objectMapper = JacksonMapper.getInstance();JsonNode jsonNode = objectMapper.readTree(jsonString);JsonNode nameNode = jsonNode.get("name");JsonNode ageNode = jsonNode.get("age");JsonNode persoNode = jsonNode.get("person");String personString = persoNode.toString();Person person = objectMapper.readValue(personString, Person.class);Log.d(TAG, "person=" + person.toString());Log.d(TAG, "age=" + ageNode.asInt());Log.d(TAG, "name=" + nameNode.asText());}

Here we use the readTree method of ObjectMapper to return a JsonNode object. Here we use the tree model parsing method, similar to the DOM in XML.

If we want to obtain data of the basic data type, we use JsonNode. get () obtains the JsonNode object containing value based on the key, and extracts the data to be obtained using as _ () based on the type. JsonNode represents a node and is a basic class of the Json tree model.

However, if you want to obtain data of a non-basic type, JsonNode does not provide the corresponding method. Therefore, you can only use the toString method of JsonNode to obtain data in Json format, then, repeat the parsing of Simple objects according to the method described above. Note that JsonNode cannot be used when we obtain data whose key is "person. asText () is obtained, because it is not a text, but another Json Object in the form of an Object, which cannot be obtained, so I use toString () to obtain it.

Of course, this is just a method I have explored, and there are other solutions, such as directly creating this type of JavaBean, but it is troublesome, the above method is more intuitive.


5. Summary

Till now, three mainstream Json parsing methods on the Android platform have been introduced. Let's summarize them:

(1) The Json class library provided by Android is inefficient and cumbersome. Reflection Parsing is not supported and is not recommended.

(2) google's Gson Parsing Library, which is a class library that I have been using before. It is easy to use and has a large amount of data. The efficiency is no problem for parsing a small amount of data. We also recommend that you use it.

(3) jackson is the most efficient resolution solution. If the data volume is large, this solution is definitely the first choice. If the data size is small, it is not very different from that of Gson.


In addition to the Jackson and Jackson described above, there are other more powerful usages. Here we will not introduce them one by one. Here are some reference urls:

(1) Jackson online documentation: http://tool.oschina.net/apidocs/apidoc? Api = jackson-1.9.9

(2) Jackson introduction of the official website translation: http://www.cnblogs.com/lee0oo0/articles/2652528.html

(3) Jackson source code view: http://www.boyunjian.com/javasrc/org.codehaus.jackson/jackson-core-lgpl/1.9.10 /_/

(4) Online Json verification: http://www.bejson.com/


Test Demo: https://github.com/ZhaoKaiQiang/JsonDemo in the article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.