Java Gson Library

Java 常用类库Java Common Libraries


Gson is a Java library provided by Google for converting Java objects to JSON representation (serialization) and converting JSON strings to Java objects (deserialization).

The main features of Gson include:

  • Simple and easy-to-use API
  • No annotations required in Java classes (but annotations are supported)
  • High performance
  • Support for generics
  • Support for custom serialization and deserialization

Core classes:

  • Gson: Main class, provides serialization and deserialization methods

  • JsonElement: Abstract class for JSON elements

  • JsonObject: JSON object representation
  • JsonArray: JSON array representation


Why use Gson?

In Java development, we often need to handle 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, and is more convenient than Java's native JSON processing.


Basic usage of Gson

Add Gson dependency

First, you need to add the Gson dependency to your project. If you use Maven, you can add it to pom.xml:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

A simple example of converting between Java and JSON objects:

Example

import com.google.gson.Gson;

public class GsonDemo {
    public static void main(String[] args) {
        Gson gson = new Gson();
       
        // Convert 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}
       
        // Convert 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 getters/setters)
    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, getters and setters 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 collection
List<Person> people = Arrays.asList(
    new Person("Wang Wu", 28),
    new Person("Zhao Liu", 32)
);
String jsonList = gson.toJson(people);

// Deserialize 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 configurations

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();
// 会将userName转换为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("Mobile 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 handling 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 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)   // Not serialized
    private String password;
   
    @Since(1.0)                  // Version control
    private String email;
}

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 Gson instances: Gson is thread-safe, so it is recommended to reuse rather than create frequently
  • For large amounts of data, consider using the streaming API (JsonReader/JsonWriter)
  • Complex object structures can affect performance

Comparison of Gson with other JSON libraries

Feature Gson Jackson org.json
Ease of use High Medium High
Performance Medium High Low
Functional 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 often the first choice for Java developers. For high-performance requirements or complex scenarios, you may considerJacksonand other libraries.

Java 常用类库Java Common Libraries

Other extensions