Java Gson Library
Gson is a Java library provided by Google for converting Java objects into their JSON representation (serialization) and converting JSON strings into Java objects (deserialization).
The main features of Gson include:
- Simple and easy-to-use API
- No need to add annotations in Java classes (but annotations are supported)
- High performance
- Supports generics
- Supports custom serialization and deserialization
** Core classes:**
-
Gson: the main class that provides serialization and deserialization methods -
JsonElement: the abstract class for JSON elements JsonObject: the representation of a JSON object
JsonArray: the representation of a JSON array
Why Use Gson?
In Java development, we often need to process JSON data in the following scenarios:
- Interacting with RESTful APIs
- Reading and writing configuration files
- Data persistence
- Data exchange between different systems
Gson provides a simple and efficient way to accomplish these tasks, which is more convenient than Java's native JSON processing.
Basic Usage of Gson
Add the Gson Dependency
First, you need to add the Gson dependency to your project. If you use Maven, you can add it to pom.xml:
com.google.code.gson
gson
2.8.9
A simple example that converts between Java and JSON objects:
Example
import
com.google.gson.Gson
;
public
class
GsonDemo
{
public
static
void
main
(
String
[
]
args
)
{
Gson gson
=
new
Gson
(
)
;
// Java object to JSON
Person person
=
new
Person
(
"Zhang San"
,
30
)
;
String
json
=
gson.
toJson
(
person
)
;
System
.
out
.
println
(
json
)
;
// Output: {"name":"Zhang San","age":30}
// JSON to Java object
Person parsedPerson
=
gson.
fromJson
(
json, Person.
class
)
;
System
.
out
.
println
(
parsedPerson.
getName
(
)
)
;
// Output: Zhang San
}
}
class
Person
{
private
String
name
;
private
int
age
;
// Constructor
public
Person
(
String
name,
int
age
)
{
this
.
name
=
name
;
this
.
age
=
age
;
}
// getter methods (Gson requires getter/setter)
public
String
getName
(
)
{
return
name
;
}
public
int
getAge
(
)
{
return
age
;
}
}
Create a Gson Instance
Gson gson
=
new
Gson
(
)
;
Java Object to JSON (Serialization)
Example
class
User
{
private
String
name
;
private
int
age
;
// Constructor, getter, and setter omitted
}
User user
=
new
User
(
"Zhang San"
,
25
)
;
String
json
=
gson.
toJson
(
user
)
;
// Output: {"name":"Zhang San","age":25}
JSON to Java Object (Deserialization)
Example
String
json
=
"{"name":"Li Si","age":30}"
;
User user
=
gson.
fromJson
(
json, User.
class
)
;
System
.
out
.
println
(
user.
getName
(
)
)
;
// Output: Li Si
Common Features
Collection Handling
Example
// Serialize a collection
List
<
Person
people
=
Arrays.
asList
(
new
Person
(
"Wang Wu"
,
28
)
,
new
Person
(
"Zhao Liu"
,
32
)
)
;
String
jsonList
=
gson.
toJson
(
people
)
;
// Deserialize a collection
Type listType
=
new
TypeToken
<
List
<
Person
(
)
{
}.
getType
(
)
;
List
<
Person
parsedPeople
=gson.
fromJson
(
jsonList, listType
)
;
Date Handling
Example
Gson gson
=
new
GsonBuilder
(
)
.
setDateFormat
(
"yyyy-MM-dd HH:mm:ss"
)
.
create
(
)
;
Date
now
=
new
Date
(
)
;
String
dateJson
=
gson.
toJson
(
now
)
;
Date
parsedDate
=
gson.
fromJson
(
dateJson,
Date
.
class
)
;
Tree Model Handling
Example
String
json
=
"{"name":"Li Si","age":25}"
;
JsonElement element
=
JsonParser.
parseString
(
json
)
;
JsonObject object
=
element.
getAsJsonObject
(
)
;
String
name
=
object.
get
(
"name"
)
.
getAsString
(
)
;
int
age
=
object.
get
(
"age"
)
.
getAsInt
(
)
;
Common Configuration
Pretty Printing
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
Null Value Handling
Gson gson = new GsonBuilder()
.serializeNulls() // 序列化null值
.create();
Field Naming Strategy
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
// Converts userName to user_name
Advanced Features of Gson
Handling Complex Objects
Gson can handle complex data structures containing nested objects, arrays, collections, etc.:
Example
class
Order
{
private
String
orderId
;
private
List
<
Product
products;
// Other code omitted
}
Order order
=
new
Order
(
"123"
,
Arrays
.
asList
(
new
Product
(
"Phone"
,
1
,
2999.00
)
,
new
Product
(
"Headphones"
,
2
,
199.00
)
)
)
;
String
json
=
gson.
toJson
(
order
)
;
Using TypeToken to Handle Generics
When you need to handle generic collections, you can use TypeToken:
Example
String
json
=
"[{"name":"Apple","price":5.5},{"name":"Banana","price":3.2}]"
;
Type productListType
=
new
TypeToken
<
List
<
Product
(
)
{
}.
getType
(
)
;
List
<
Product
products
=gson.
fromJson
(
json, productListType
)
;
Custom Serialization and Deserialization
You can customize the processing logic by implementing the JsonSerializer and JsonDeserializer interfaces:
Example
public
class
DateSerializer
implements
JsonSerializer
<
Date
{
private
static
final
SimpleDateFormat
format
=
new
SimpleDateFormat
(
"yyyy-MM-dd"
);
@Override
public
JsonElement serialize
(
Date
date, Type type, JsonSerializationContext context
)
{
return
new
JsonPrimitive
(
format.
format
(
date
)
)
;
}
}
// Use a custom serializer
Gson gson
=
new
GsonBuilder
(
)
.
registerTypeAdapter
(
Date
.
class
,
new
DateSerializer
(
)
)
.
create
(
)
;
Using Annotations
Gson provides some useful annotations:
Example
class
User
{
@SerializedName
(
"user_name"
)
// JSON field name
private
String
name
;
@Expose
(
serialize
=
false
)
// Excluded from serialization
private
String
password
;
@Since
(
1.0
)
// Version control
private
String
;
}
GsonBuilder Configuration
GsonBuilder provides various configuration options:
Example
Gson gson
=
new
GsonBuilder
(
)
.
setPrettyPrinting
(
)
// Pretty printing
.
serializeNulls
(
)
// Serialize null values
.
setDateFormat
(
"yyyy-MM-dd"
)
// Date format
.
disableHtmlEscaping
(
)
// Disable HTML escaping
.
create
(
)
;
Performance considerations
- Reuse the Gson instance: Gson is thread-safe, so reuse is recommended instead of frequent creation
- For large amounts of data processing, consider using the streaming API (JsonReader/JsonWriter)
- Complex object structures will affect performance
Comparison of Gson with Other JSON Libraries
| Feature | Gson | Jackson | org.json |
|---|---|---|---|
| Ease of Use | High | Medium | High |
| Performance | Medium | High | Low |
| Feature Completeness | High | Very high | Low |
| Community Support | High | Very high | Medium |
Summary
Gson is a powerful yet simple JSON processing library suitable for most Java projects. It provides:
- Simple API design
- Flexible configuration options
- Good performance
- Rich features
For simple JSON processing needs, Gson is usually the first choice of Java developers. For high-performance requirements or complex scenarios, you can consider Jackson and other libraries.
Common Java Libraries