Example of basic usage of JSON conversion library gson in Java

GitHub page for downloading and deploying gson: https://github.com/google/gson Before working with the gson API, you need to download the library (jar file) and include it in the classpath. Libraries, along with source code and Java documentation, are available from http://code.google.com/p/google-gson/downloads/list Download. After downloading, add gson - < version > Jar to classpath. For those readers who prefer to use Maven to manage dependencies (JAR files), add the following dependencies to POM xml。

< version > 2.2 needs to be modified 4。 All code examples in this article use the versions listed above. pom. A copy of the XML file can be found here.

If this library is used for web applications, make sure to keep a copy in the WEB-INF / lib folder. Alternatively, the gson library can be placed in the application server and provided to web applications.

Example

Here is a simple example:

The entity is very simple. There are two fields. Of course, the fields in the entity can also be of type list or set.

The above code focuses on the gson object, which provides the tojason () method to convert the object into a JSON string. The str object value of the above code is:

[{"name":"name0","age":0},{"name":"name1","age":5},{"name":"name2","age":10},{"name":"name3","age":15},{"name":"name4","age":20},{"name":"name5","age":25},{"name":"name6","age":30},{"name":"name7","age":35},{"name":"name8","age":40},{"name":"name9","age":45}]

Very standard JSON data, very simple, ha ha.

Let's take a look at the deserialization of gson. Gson provides the fromjson () method to implement the method from JSON related objects to Java entities.

In daily application, we usually encounter two situations: converting to a single entity object and converting to an object list or other structure.

Let's start with the first:

For example, the JSON string is:

code:

Two parameters are provided, namely JSON string and the type of object to be converted.

Second, convert to list type:

code:

You can see that the above code uses typetoken, which is a data type converter provided by gson and can support various data collection type conversion.

There are so many basic uses of gson. For annotation, please refer to gson's official documents. I hope it can be helpful to beginners of Java and gson.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>