Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Gson in Java

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "how to use Gson in Java", the content is easy to understand, clear, hope to help you solve doubts, the following let the editor lead you to study and learn "how to use Gson in Java" this article.

JSON is a text-based data exchange format, which is lighter than XML, easier to read and write than binary, and more convenient for modulation. There are many ways to parse and generate, the most commonly used class libraries in Java are: JSON-Java, Gson, Jackson, FastJson, etc.

I. the basic usage of Gson

Gson provides two direct parsing and generation methods, fromJson () and toJson (), the former for deserialization and the latter for serialization, and each method provides overloaded methods

(1) parsing of basic data types

Gson gson = new Gson (); int I = gson.fromJson ("100s", int.class); / / 100double d = gson.fromJson ("\" 99.99\ ", double.class); / / 99.99boolean b = gson.fromJson (" true ", boolean.class); / / trueString str = gson.fromJson (" String ", String.class); / / String

(2) Generation of basic data types

Gson gson = new Gson (); String jsonNumber = gson.toJson (100); / / 100String jsonBoolean = gson.toJson (false); / / falseString jsonString = gson.toJson ("String"); / / "String"

(3) Generation and parsing of POJO class

Public class User {/ / omit other public String name; public int age; public String emailAddress;}

Generate JSON:

Gson gson = new Gson (); User user = new User (Zhang San, 24); String jsonObject = gson.toJson (user); / / {"name": "Zhang San kidou", "age": 24}

Parse JSON:

Gson gson = new Gson (); String jsonString = "{\" name\ ":\" Zhang San\ ",\" age\ ": 24}"; User user = gson.fromJson (jsonString, User.class)

Second, the use of @ SerializedName annotation for attribute renaming

From the generation and parsing of the above POJO, we can see that the names and types of the fields and values of json correspond one to one, but there is also a certain fault-tolerant mechanism (for example, line 3 of the first example converts 99.99 of the string to string), but sometimes some discordant situations occur, such as:

Expected json format: {"name": "Zhang San", "age": 24, "emailAddress": "zhangsan@ceshi.com"}

Actual: {"name": "Zhang San", "age": 24, "email_address": "zhangsan@ceshi.com"}

Gson needs to use reflection in serialization and deserialization. Generally, all kinds of libraries liberate their notes to the annotations package. Open the source code there is an annotations under the com.google.gson package, and there is a SerializedName annotation class in it. For the attribute email_address in json that corresponds to POJO, the attribute becomes:

@ SerializedName ("email_address") public String emailAddress

Provide an alternative property name for the POJO field: the SerializedName annotation provides one of two properties, one of which is used, and an attribute, alternate, that receives an array of String

Note: version 2.4 is required for alternate

@ SerializedName (value = "emailAddress", alternate = {"email", "email_address"}) public String emailAddress;// can get the correct result when any of the three properties (email_address, email, emailAddress) appear / / when multiple cases occur at the same time, the value of the last occurrence shall prevail. Gson gson = new Gson (); String json = "{\" name\ ":\" Zhang Sankidou\ ",\" age\ ": 24,\" emailAddress\ ":\" zhangsan@ceshi.com\ ",\" email\ ":\" zhangsan_2@ceshi.com\ ",\" email_address\ ":\" zhangsan_3@ceshi.com\ "}"; User user = gson.fromJson (json, User.class); System.out.println (user.emailAddress); / / zhangsan_3@example.com

III. Using generics in Gson

For example: JSON string array: ["Android", "Java", "PHP"]

When you want to parse the json through Gson, there are generally two ways: using arrays, using List;, and List is more convenient for adding and deleting, so the actual use is still more than List.

The array is relatively simple:

Gson gson = new Gson (); String jsonArray = "[\" Android\ ",\" Java\ ",\" PHP\ "]"; String [] strings = gson.fromJson (jsonArray, String [] .class)

It is not possible for List to change the String [] .class in the above code directly to List.class. For Java, there is only one bytecode file for List and List, and that is List.class. This is the problem of generic erasure when using Java generics.

In order to solve the above problem, Gson provides TypeToken to support generics, so you need to write this when parsing the above data to List

Gson gson = new Gson (); String jsonArray = "[\" Android\ ",\" Java\ ",\" PHP\ "]"; String [] strings = gson.fromJson (jsonArray, String [] .class); List stringList = gson.fromJson (jsonArray, new TypeToken () {} .getType ()); / / the construction method of TypeToken is modified by protected, so it is written as new TypeToken () {} .getType () instead of new TypeToken (). GetType ()

The influence of generic parsing on the Design of Interface POJO

The introduction of generics reduces extraneous code:

{"code": "0", "message": "success", "data": {}} {"code": "0", "message": "success", "data": []}

The data contained in data that we really need is only used once by code and hardly used by message. If Gson does not support generics or students who do not know that Gson supports generics, they will define POJO this way.

Public class UserResponse {public int code; public String message; public User data;}

When other APIs are used, a XXResponse is redefined to change the type of data to XX. Obviously, code and message are repeatedly defined. Through generics, code and message fields can be extracted into a Result class, so you only need to write the POJO corresponding to the data field:

Public class Result {public int code; public String message; public T data;} / / can be written as Result if the data field is User and Result when it is a list

IV. Stream deserialization of Gson

(1) automatic mode

Gson provides fromJson (), which implements deserialization, and toJson (), which implements serialization, and toJson (), which is directly used for parsing and generation. At the same time, each method provides an overloaded method.

Gson.toJson (Object); Gson.fromJson (Reader,Class); Gson.fromJson (String,Class); Gson.fromJson (Reader,Type); Gson.fromJson (String,Type)

(2) Manual method: the manual way is to use the JsonReader class under the stream package to manually deserialize, which is similar to using pull to parse XML in Android

String json = "{\" name\ ":\" Zhang San\ ",\" age\ ":\" 24\ "}"; User user = new User (); JsonReader reader = new JsonReader (new StringReader (json)); reader.beginObject (); while (reader.hasNext ()) {String s = reader.nextName (); switch (s) {case "name": user.name = reader.nextString (); break; case "age": user.age = reader.nextInt (); / / automatic conversion break Case "email": user.email = reader.nextString (); break;}} reader.endObject (); / / throws IOExceptionSystem.out.println (user.name); / / Zhang San System.out.println (user.age); / / 24System.out.println (user.email); / / zhangsan@ceshi.com

Automatic methods are ultimately achieved through JsonReader. If the first parameter is of type String, then Gson will create a StringReader to convert to a stream operation.

Stream serialization of Gson

(1) automatic mode

Gson.toJson method list

/ / PrintStream (System.out), StringBuilder, StringBuffer and * Writer all implement the Appendable interface. Gson gson = new Gson (); User user = new User ("Zhang San", 24, "zhangsan@ceshi.com"); gson.toJson (user,System.out)

(2) manual mode

JsonWriter writer = new JsonWriter (new OutputStreamWriter (System.out)); writer.beginObject () / / throws IOException .name ("name"). Value ("Zhang San") .name ("age"). Value (24) .name ("email"). NullValue () / demo null .endObject (); / / throws IOException writer.flush () / / throws IOException// {"name": "Zhang San", "age": 24, "email": null} / / in addition to beginObject, endObject, beginArray and endArray, the two can be nested with each other, just pay attention to pairing. The name method cannot be called after beginArray, and the name method must be called before calling value after beginObject.

Use GsonBuilder to export null values, format output, date and time

In general, the API provided by the Gson class can already meet most usage scenarios, but sometimes when more special and powerful features are needed, a new class GsonBuilder is introduced.

GsonBuilder can also be known by name as a class used to build Gson instances. To change the default settings of Gson, you must use this class to configure Gson.

GsonBuilder usage:

/ / various configurations / / generate configured GsonGson gson = new GsonBuilder () .create ()

(1) by default, Gson does not export the key of the value null, such as:

Public class User {public String name; public int age; / / omit public String email;} Gson gson = new Gson (); User user = new User (Zhang San ", 24); System.out.println (gson.toJson (user)); / / {" name ":" Zhang San "," age ": 24} / / the field does not appear in json, which is useful when you need to export a complete json string during debugging or when no value must be used in API connection.

How to use it:

Gson gson = new GsonBuilder (). SerializeNulls (). Create (); User user = new User ("Zhang San", 24); System.out.println (gson.toJson (user)); / / {"name": "Zhang San", "age": 24, "email": null}

Format output, date, time, and others:

Gson gson = new GsonBuilder () / serialize null .serializeNulls () / / format the date and time There are two other overloaded methods / / effective during serialization and deserialization. SetDateFormat ("yyyy-MM-dd") / disable this serialization inner class. Serialization () / generate an unexecutable Json (too many)]} 'these four characters) .generateNonExecutableJson () / forbids escaping html tags .setleHtmlEscaping () / format output .setPrettyPrinting () .create () / /: difference between inner class (Inner Class) and nested class (Nested Class)

The above is all the contents of the article "how to use Gson in Java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report