In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces how to use Gson in Java Json API, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
GSON is a Java API developed by Google to transform Java objects and Json objects.
Download and install
Before you can work with GSON API, you need to download the library (jar file) and include it in the classpath. The library, 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-.jar to the classpath. For those readers who prefer to use Maven to manage dependencies (JAR files), add the following dependencies to pom.xml.
Com.google.code.gson gson 2.2.4
2.2.4 needs to be modified. All code examples in this article use the versions listed above. A copy of the pom.xml file can be found here.
If this library is used for web applications, be sure to keep a copy in the WEB-INF/lib folder. Alternatively, the GSON library can be placed on the application server and made available to web applications.
A simple example
GSON API provides a class file, Gson (Java document), which is used to handle the conversion of Java and JSON objects. You can call the default constructor, or in the form of the following code, to create an instance of this class using the GsonBuilder (Java document) class. 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; public class SimpleExample1 {public static void main (String [] args) {Gson gson = new GsonBuilder (). Create (); gson.toJson ("Hello", System.out); gson.toJson (123, System.out);}}
In the above example, we created an instance of Gson and converted Java String and int into JSON objects. The output from the command line of the above code is as follows:
"Hello" 123
It's not rocket science, but it's a start. Note that the above results are entered on the command line. The toJason () method takes two parameters, an Java object converted to JSON and an instance of an appendable (Java's 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 ();}}
Be careful
Why are variables declared to be of type Writer when the actual type is FileWriter?
It's a good idea to use generics as much as possible. In the above example, we only use the methods defined by the Appendable and Writer interfaces. Here is a bad example of using generics to make your code easier to port and maintain.
Note that in the above example, we did not handle the Writer correctly. Ideally, resources are turned off in finaly blocks or used in try-with-resource (tutorials). We ignored this to keep the code concise. \
Public static void main (String [] args) throws IOException {try (Writer writer = new FileWriter ("Output.json")) {Gson gson = new GsonBuilder (). Create (); gson.toJson ("Hello", writer); gson.toJson (123, writer);}}
The above code generation file: the Output.json containing the JSON object. Note that we use a character stream instead of a byte stream here. Because the toJson () method requires an Appendanble instance, and the byte stream does not implement the Appendable interface, we use the character stream. The Appendable interface handles characters instead of bytes. Java provides InputStreanReader (Java document) and OutputStreamWriter (Java document) classes to convert byte streams to character streams, as in the following example.
Be careful
Note that when using the InputStreamREader and OutputStreamWriter classes, if no encoding or character set is provided, the conversion uses the platform default character set. This will reduce the portability of the code, and running on other platforms may result in 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 ("Output.json"), "UTF-8") {Gson gson = new GsonBuilder () .create () Gson.toJson ("Hello", writer); gson.toJson (123, writer);}
As you can see, we only need to change part of the example. Nothing has changed in the rest of the code. 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. Suppose the web server produces the following JSON object when querying:
{NAME: "Albert Attard", P_LANGUAGE: "Java", LOCATION: "Malta"}
This JSON object contains three fields with different values. For example, we need to use the JSON object and create a Java object to display it. To make this example more interesting, suppose we only care about the name and location domains.
First create a Java class to represent name and location. Class is named Person. The name of the class does not matter, but the name of the domain must be consistent. The domain name must match the name in the JSON object (case sensitive). Further, the class must contain a default constructor (even if it is set to private). As shown below, the name and location fields are uppercase in JSON. The domain P_LANGUAGE in JSON is ignored because the domain with that name is not included in the Java object. Please understand that domain names do not comply with the Java naming convention, for the time being, it is only for simplification. More will be discussed in part 2.
Package com.javacreed.examples.gson.part2; public class Person {private String NAME; private String LOCATION; / / Getters and setters are not required for this example. / / GSON sets the fields directly using reflection. @ Override public String toString () {return NAME + "-" + 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. In order to simulate the real situation, we use byte stream as input. Also note that the JSON content is saved in a file in the resource folder (this is not a normal 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; public class JsonToJava {public static void main (String [] args) throws 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, which is printed to the command line.
Nesting JSON objects
Let's take the above example a step further. The JSON code snippet shown 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, SUBJECT and GRADE. We need to modify the definition of the Person class to include the exam domain and create a new Java class to represent EXAM, which contains the SUBJECT and graded fields.
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 JSON.
Package com.javacreed.examples.gson.part3; public class Exam {private String SUBJECT; private double GRADE; / / Getters and setters are 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, with the type Exam. Notice that the following Person class is located in a different package than the previous one.
Package com.javacreed.examples.gson.part3; public class Person {private String NAME; private String LOCATION; private Exam EXAM; @ Override public String toString () {return NAME + "-" + LOCATION + "(" + EXAM + ")";}}
Note that the changes required are minimal because Gson dynamically discovers (using reflection) the class and its domain. Reflection is not included in this article. For more information about reflection, please refer to: Reflection in Action.
*, let's try new changes.
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; public class JsonToJava {public static void main (String [] args) throws 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 has not changed because Gson uses the model (Person and Exam classes) to map Json to Java.
Conclusion
Even though JSON may be a new concept, it is very simple and straightforward. In addition, compared with the bulky XML that needs to add tags for message / data conversion, it is more popular because of simplicity. It is important to note that JSON is a subset of JavaScript, and JavaScript uses it as a solution for data exchange, such as web pages. GSON API makes it easier to use, and even if it's not discussed here, it provides powerful flexibility.
Thank you for reading this article carefully. I hope the article "how to use Gson in Java Json API" shared by the editor will be helpful to everyone. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.