gson
A Java serialization/deserialization library to convert Java Objects into JSON and back
Top Related Projects
Main Portal page for the Jackson project
FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
A modern JSON library for Kotlin and Java.
jsoniter (json-iterator) is fast and flexible JSON parser available in Java and Go
A reference implementation of a JSON package in Java.
Quick Overview
Gson is a Java library developed by Google for converting Java Objects into their JSON representation and vice versa. It provides a simple and efficient way to serialize Java objects to JSON and deserialize JSON strings back into Java objects, making it an essential tool for working with JSON data in Java applications.
Pros
- Easy to use with minimal setup required
- Supports complex object hierarchies and nested objects
- Highly customizable with type adapters and custom serialization/deserialization
- Performs well in terms of speed and memory usage
Cons
- Limited support for certain Java-specific features like transient fields
- Can be challenging to handle complex generic types
- Lacks built-in support for some advanced JSON features like JSON schema validation
Code Examples
- Serializing a Java object to JSON:
Gson gson = new Gson();
Person person = new Person("John Doe", 30);
String json = gson.toJson(person);
System.out.println(json);
// Output: {"name":"John Doe","age":30}
- Deserializing JSON to a Java object:
String json = "{\"name\":\"Jane Smith\",\"age\":25}";
Gson gson = new Gson();
Person person = gson.fromJson(json, Person.class);
System.out.println(person.getName() + " is " + person.getAge() + " years old.");
// Output: Jane Smith is 25 years old.
- Working with generic types:
Type listType = new TypeToken<List<Person>>(){}.getType();
String json = "[{\"name\":\"Alice\",\"age\":28},{\"name\":\"Bob\",\"age\":32}]";
Gson gson = new Gson();
List<Person> people = gson.fromJson(json, listType);
people.forEach(p -> System.out.println(p.getName()));
// Output:
// Alice
// Bob
Getting Started
To use Gson in your Java project, first add the dependency to your build file. For Maven:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
For Gradle:
implementation 'com.google.code.gson:gson:2.10.1'
Then, you can start using Gson in your Java code:
import com.google.gson.Gson;
public class Example {
public static void main(String[] args) {
Gson gson = new Gson();
// Use gson for JSON operations
}
}
Competitor Comparisons
Main Portal page for the Jackson project
Pros of Jackson
- More flexible and feature-rich, supporting various data formats beyond JSON
- Better performance, especially for large datasets
- More customization options and annotations for fine-grained control
Cons of Jackson
- Steeper learning curve due to its extensive feature set
- More complex configuration and setup compared to Gson
- Larger library size, which may impact application size
Code Comparison
Jackson:
ObjectMapper mapper = new ObjectMapper();
MyObject obj = mapper.readValue(jsonString, MyObject.class);
String json = mapper.writeValueAsString(obj);
Gson:
Gson gson = new Gson();
MyObject obj = gson.fromJson(jsonString, MyObject.class);
String json = gson.toJson(obj);
Both libraries offer straightforward serialization and deserialization, but Jackson provides more advanced features and configurations. Gson is simpler to use out of the box, while Jackson offers greater flexibility and performance at the cost of increased complexity.
Jackson is generally preferred for larger, more complex projects that require advanced features and customization. Gson is often chosen for simpler applications or when ease of use is a priority. The choice between the two depends on the specific requirements of your project and the level of control you need over the JSON processing.
FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
Pros of fastjson
- Faster parsing and serialization performance
- Supports more data types and complex object structures
- More flexible configuration options for customization
Cons of fastjson
- Less mature and stable compared to gson
- Potential security vulnerabilities (historically)
- Less documentation and community support
Code Comparison
fastjson:
JSON.parseObject(jsonString, MyClass.class);
String jsonOutput = JSON.toJSONString(myObject);
gson:
Gson gson = new Gson();
MyClass obj = gson.fromJson(jsonString, MyClass.class);
String jsonOutput = gson.toJson(myObject);
Both libraries offer similar basic functionality for JSON parsing and serialization. fastjson tends to have a more concise syntax, while gson provides a more object-oriented approach with the Gson class.
fastjson generally offers better performance, especially for large datasets or complex objects. However, gson is known for its stability, widespread adoption, and better documentation.
When choosing between the two, consider factors such as performance requirements, project complexity, and the need for specific features or customizations. gson might be preferable for simpler projects or those prioritizing stability, while fastjson could be advantageous for high-performance scenarios or projects requiring advanced features.
A modern JSON library for Kotlin and Java.
Pros of Moshi
- Better performance, especially for large JSON payloads
- Built-in Kotlin support with codegen for creating type-safe adapters
- More flexible API for custom adapters and annotations
Cons of Moshi
- Smaller community and ecosystem compared to Gson
- Steeper learning curve for advanced features
- Less documentation and fewer examples available online
Code Comparison
Gson:
Gson gson = new Gson();
User user = gson.fromJson(jsonString, User.class);
String json = gson.toJson(user);
Moshi:
val moshi = Moshi.Builder().build()
val adapter = moshi.adapter(User::class.java)
val user = adapter.fromJson(jsonString)
val json = adapter.toJson(user)
Both libraries offer similar basic functionality for JSON serialization and deserialization. Gson provides a simpler API out of the box, while Moshi requires a bit more setup but offers more flexibility and better performance in many cases. Moshi's Kotlin support is a significant advantage for Kotlin developers, while Gson's larger ecosystem and extensive documentation make it easier for beginners to get started.
jsoniter (json-iterator) is fast and flexible JSON parser available in Java and Go
Pros of json-iterator/java
- Significantly faster performance, especially for large JSON payloads
- More memory-efficient, with lower allocation rates
- Supports streaming for handling very large JSON files
Cons of json-iterator/java
- Less mature and less widely adopted compared to gson
- Fewer built-in type adapters and customization options
- May require more manual configuration for complex use cases
Code Comparison
gson:
Gson gson = new Gson();
MyObject obj = gson.fromJson(jsonString, MyObject.class);
String json = gson.toJson(obj);
json-iterator/java:
JsonIterator iter = JsonIterator.parse(jsonString);
MyObject obj = iter.read(MyObject.class);
String json = JsonStream.serialize(obj);
Both libraries offer similar ease of use for basic JSON serialization and deserialization. However, json-iterator/java provides additional methods for performance optimization, such as using byte arrays directly:
byte[] bytes = jsonString.getBytes();
MyObject obj = JsonIterator.deserialize(bytes, MyObject.class);
While gson is more established and feature-rich, json-iterator/java offers superior performance for high-throughput applications. The choice between the two depends on specific project requirements, with gson being more suitable for general use cases and json-iterator/java excelling in performance-critical scenarios.
A reference implementation of a JSON package in Java.
Pros of JSON-java
- Lightweight and simple to use, with a straightforward API
- No external dependencies, making it easy to integrate into projects
- Supports both JSON parsing and generation
Cons of JSON-java
- Less feature-rich compared to Gson, lacking advanced serialization/deserialization options
- Not as actively maintained, with fewer updates and contributions
- Limited support for custom type adapters and complex object mapping
Code Comparison
JSON-java:
JSONObject obj = new JSONObject();
obj.put("name", "John");
obj.put("age", 30);
String jsonString = obj.toString();
Gson:
Gson gson = new Gson();
Person person = new Person("John", 30);
String jsonString = gson.toJson(person);
Summary
JSON-java is a simple, lightweight library for JSON processing in Java, while Gson offers more advanced features and better object mapping capabilities. JSON-java is suitable for basic JSON operations, but Gson provides more flexibility and power for complex use cases. The choice between the two depends on the specific requirements of your project and the level of JSON manipulation needed.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Gson
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.
[!NOTE]
Gson is currently in maintenance mode; existing bugs will be fixed, but large new features will likely not be added. If you want to add a new feature, please first search for existing GitHub issues, or create a new one to discuss the feature and get feedback.
[!IMPORTANT]
Gson's main focus is on Java. Using it with other JVM languages such as Kotlin or Scala might work fine in many cases, but language-specific features such as Kotlin's non-null
types or constructors with default arguments are not supported. This can lead to confusing and incorrect behavior.
When using languages other than Java, prefer a JSON library with explicit support for that language.
Goals
- Provide simple
toJson()
andfromJson()
methods to convert Java objects to JSON and vice-versa - Allow pre-existing unmodifiable objects to be converted to and from JSON
- Extensive support of Java Generics
- Allow custom representations for objects
- Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
Download
Gradle:
dependencies {
implementation 'com.google.code.gson:gson:2.11.0'
}
Maven:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.11.0</version>
</dependency>
Gson jar downloads are available from Maven Central.
Requirements
Minimum Java version
- Gson 2.12.0 and newer: Java 8
- Gson 2.9.0 to 2.11.0: Java 7
- Gson 2.8.9 and older: Java 6
Despite supporting older Java versions, Gson also provides a JPMS module descriptor (module name com.google.gson
) for users of Java 9 or newer.
JPMS dependencies (Java 9+)
These are the optional Java Platform Module System (JPMS) JDK modules which Gson depends on. This only applies when running Java 9 or newer.
-
java.sql
(optional since Gson 2.8.9)
When this module is present, Gson provides default adapters for some SQL date and time classes. -
jdk.unsupported
, respectively classsun.misc.Unsafe
(optional)
When this module is present, Gson can use theUnsafe
class to create instances of classes without no-args constructor. However, care should be taken when relying on this.Unsafe
is not available in all environments and its usage has some pitfalls, seeGsonBuilder.disableJdkUnsafe()
.
Minimum Android API level
- Gson 2.11.0 and newer: API level 21
- Gson 2.10.1 and older: API level 19
Older Gson versions may also support lower API levels, however this has not been verified.
Documentation
- API Javadoc: Documentation for the current release
- User guide: This guide contains examples on how to use Gson in your code
- Troubleshooting guide: Describes how to solve common issues when using Gson
- Releases and change log: Latest releases and changes in these versions; for older releases see
CHANGELOG.md
- Design document: This document discusses issues we faced while designing Gson. It also includes a comparison of Gson with other Java libraries that can be used for Json conversion
Please use the 'gson' tag on StackOverflow, GitHub Discussions or the google-gson Google group to discuss Gson or to post questions.
Related Content Created by Third Parties
- Gson Tutorial by
StudyTrails
- Gson Tutorial Series by
Future Studio
- Gson API Report
Building
Gson uses Maven to build the project:
mvn clean verify
JDK 11 or newer is required for building, JDK 17 or 21 is recommended. Newer JDKs are currently not supported for building (but are supported when using Gson).
Contributing
See the contributing guide.
Please perform a quick search to check if there are already existing issues or pull requests related to your contribution.
Keep in mind that Gson is in maintenance mode. If you want to add a new feature, please first search for existing GitHub issues, or create a new one to discuss the feature and get feedback.
License
Gson is released under the Apache 2.0 license.
Copyright 2008 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Disclaimer
This is not an officially supported Google product.
Top Related Projects
Main Portal page for the Jackson project
FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
A modern JSON library for Kotlin and Java.
jsoniter (json-iterator) is fast and flexible JSON parser available in Java and Go
A reference implementation of a JSON package in Java.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot