Java Json Api:gson Use easy to get started

Source: Internet
Author: User
Tags tojson

Gson is a Java API developed by Google to transform Java objects and JSON objects. This article discusses and provides a simple code example that uses the API. More APIs about Gson can be accessed by: http://sites.google.com/site/gson/.

This article is the first article in the Gson series. This article is the basis of other articles and therefore does not require any gson or JSON experience. The second article provides an example of Gson deserialization (from JSON to Java), and the third article provides an example of Gson serialization (from Java to JSON).

All of the code listed below is available in Https://java-creed-examples.googlecode.com/svn/gson/Simple%20Gson%20Example. Found it. Most of the examples do not contain all the code, and some fragments may be ignored, regardless of the example discussed. Readers can download or review all the code from the links above.

The reader needs basic Java (tutorial) knowledge and a very basic maven (home) knowledge. The code shown here uses Maven to download the Gson library. Import the project into SpringSource Tool Suite (the recommended IDE) without any configuration.

Download and install

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, can be downloaded from http://code.google.com/p/google-gson/downloads/list. When the download is complete, add Gson-<version>.jar to the classpath. For those readers who prefer to use MAVEN to manage Dependencies (jar files), add the following dependencies to Pom.xml.

<dependency>    <groupid>com.google.code.gson</<Artifactid>gson </<version>2.2.4</version></dependency>  

Need to modify<version>2.2.4</version>。本文所有代码示例使用上面列出的版本。pom.xml文件拷贝可以在这里找到。

If the library is for a web app, make sure to keep a copy in the Web-inf/lib folder. Alternatively, the Gson library can be placed on the application server to provide to the Web App.

A simple example

The Gson API provides a class file, Gson (Java document), which is used to handle the conversion of Java and JSON objects. You can use the Gsonbuilder (Java document) class to create an instance of this class by invoking the default constructor, or in the form of the following code. The Gsonbuilder class is customizable and allows developers to instantiate Gson on demand.

Package com.javacreed.examples.gson.part1; import Com.google.gson.Gson; import Com.google.gson.GsonBuilder; mainNew Gsonbuilder (). Create (); Gson.tojson ("Hello", System.out); Gson.tojson (123, System.out);}} 

In the example above, we created a Gson instance and converted Java strings and int to JSON objects. The output from the above code command line is as follows:

"Hello"123

It's not rocket science, but it's a start. Note that the above results are entered into the command line. The Tojason () method has two parameters, and the Java object is converted to an instance of JSON and an appended (Java document). We can easily change a file or network stream.

Package com.javacreed.examples.gson.part1;Import Java.io.FileWriter;Import java.io.IOException;import Java.io.Writer; import Com.google.gson.Gson; import Com.google.gson.GsonBuilder; public class SimpleExample2 { public static void Main (string[] args) throws  IOException { writer writer = new FileWriter ("Output.json"); Gson Gson = new Gsonbuilder (). Create (); Gson.tojson ("Hello", writer); Gson.tojson (123, writer); Writer.close (); }}
Note

Why is a variable declared as a writer type, while the actual type is FileWriter?

It's a good way to use generics as much as possible. In the example above, we only used the methods defined by the appendable and writer interfaces. Using generics to make your code easier to transplant and maintain, here's a bad example.

Note that in the above example, we do not handle the stream correctly (Writer). Ideally, the resource is closed in the finaly block (tutorial) or used in Try-with-resource (tutorial). We've overlooked this to keep the code simple.

Mainnew FileWriter (new Gsonbuilder (). Create (); Gson.tojson ("Hello", writer); Gson.tojson ( 123, writer); }}

The above code generation file: Contains the JSON object's Output.json. Note that we use a character stream instead of a byte stream. Because the Tojson () method requires a appendanble instance, and the byte stream cannot implement the Appendable interface, we use a character stream. The Appendable interface handles characters rather than bytes. Java provides inputstreanreader (Java documentation) and OutputStreamWriter (Java document) classes for converting byte streams to characters, as in the following example.

Attention

Note that when using the InputStreamReader and OutputStreamWriter classes, if no encoding or character set is provided, the conversion will use the platform default character set. This will reduce the portability of your code, and running on other platforms may cause incorrect behavior.

Package com.javacreed.examples.gson.part1;Import Java.io.FileOutputStream;Import java.io.IOException;Import Java.io.OutputStreamWriter;Import Java.io.Writer;Import Com.google.gson.Gson;import com.google.gson.GsonBuilder; public class simpleexample3 {public static void Main (string[] args) throws IOException {try (writer Writer = new  OutputStreamWriter (New fileoutputstream ( "Output.json"),  "UTF-8")) {gson Gson = new gsonbuilder (). Create (); Gson.tojson ( "Hello", writer), Gson.tojson (123, writer);}}   

As you can see, we just need to change the part of the instance. The remainder of the code does not change. This is one of the benefits of using interfaces instead of classes as variable types.

Working with JSON objects

For example, we need to use JSON objects and load them as Java objects. Assume that a Web server query produces the following JSON object:

{  NAME:"Albert Attard",  p_language:"Java", location  :"Malta"}   

This JSON object contains 3 fields of different values. For example, we need to use a JSON object and create a Java object to show it. To make this example more interesting, let's say we only care about the name and location domain.

First, create a Java class to represent name and location. Class is named person. The name of the class does not matter, but the domain name must be the same. The domain name must match (case sensitive) the name in the JSON object. Further, the class must contain a default constructor (even if it is set to private). The name and location fields are capitalized in JSON, as shown below. The domain P_language in JSON is ignored because the domain of that name is not included in the Java object. Please understand that domain names do not adhere to the Java naming conventions for the time being simply simplified. More content will be discussed in part 2nd.

Package com.javacreed.examples.gson.part2; Person    {    toString'-' + location;}}  

Once the Java object is ready, we can read the JSON object and load it as a Java object, as shown in the following code. To simulate the real situation, we used a byte stream as input. Also note that the JSON content is stored in the files in the resource folder (this is not a common practice).

Package com.javacreed.examples.gson.part2;Import java.io.IOException;Import Java.io.InputStreamReader;Import Java.io.Reader;Import Com.google.gson.Gson;Import Com.google.gson.GsonBuilder;Publicclass jsontojava {public static void Main (string[] args) throws Span class= "Hljs-type" >ioexception {try (reader Reader = new inputstreamreader (jsontojava. Class.getresourceasstream ( "/server1.json"),  "UTF-8")) {gson Gson = new gsonbuilder (). Create (); person p = Gson.fromjson (reader, person. Class); system.out. println (p);} }} 

The output is as follows:

Albert Attard-malta

Gson parses the JSON object and creates an instance of the person class and prints it to the command line.

Nested JSON objects

Let's take a closer look at the example above, and the JSON snippet below contains a nested object.

{  NAME:"Albert Attard",  p_language:"Java", location  :"Malta",  EXAM: {    SUBJECT :"Programming",    GRADE:4.5}}     

The exam domain consists of two domains, each of which is aSUBJECT和GRADE。我们需要修改Person类的定义来包含EXAM域,并创建一个新的Java类来表示EXAM,该类包含SUBJECT和GRADE域。

We first create a new class to represent nested objects. As discussed earlier, the class name does not matter, but the domain name must match the domain name in the JSON.

package com.javacreed.examples.gson.part3; Public class exam {private String SUBJECT; private double GRADE; //Getters and setters is not required for this example. //Gson sets the fields directly using reflection.  @Override public String tostring () {return SUBJECT + "-"+ GRADE;}}              

Now we can modify the person class to introduce a field with the same name as exam in JSON, type exam. Note that the following person class is associated with the previous <span style= "color: #ff0000;" > is located in </span> different packages.

Package com.javacreed.examples.gson.part3; Person    {    toString")";}}  

Note that the desired change is minimal, because Gson dynamically discovers (uses reflection) the class and its domain. This article does not contain reflections, for more information on reflection, refer to: Reflection in Action.

Finally, let's try a new change.

Package com.javacreed.examples.gson.part3;Import java.io.IOException;Import Java.io.InputStreamReader;Import Java.io.Reader;Import Com.google.gson.Gson;Import Com.google.gson.GsonBuilder;Publicclass jsontojava {public static void Main (string[] args) throws Span class= "Hljs-type" >ioexception {try (reader Reader = new inputstreamreader (jsontojava. Class.getresourceasstream ( "/server2.json"),  "UTF-8")) {gson Gson = new gsonbuilder (). Create (); person p = Gson.fromjson (reader, person. Class); system.out. println (p);} }} 

The Jsontojava class did not make any changes because Gson used the model (person and exam Class) to map the JSON to Java.

Conclusion

Even though JSON may be a new concept, it is very simple and straightforward. In addition, it is more popular because of its simplicity compared to the cumbersome XML that needs to increase the label for message/Data conversion. It is necessary to point out that JSON is a subset of JavaScript, and JavaScript makes it a perfect solution for exchanging data, such as Web pages. The Gson API makes it easier to use, even if there is no part to discuss here, and it provides a great deal of flexibility.

For more Gson examples, please step 2nd, we will explore more complex examples and discuss how to use the Gson Deserializer to fully control the deserialization process.

Java Json Api:gson Use easy to get started

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.