gson README

The project's README from github.com/google/gson. As one markdown file: README.md.

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.

[!IMPORTANT]
Gson is not a recommended library for interacting with JSON on Android. The open-ended reflection in the Gson runtime doesn't play nicely with shrinking/optimization/obfuscation passes that Android release apps should perform.
If your app or library may be running on Android, consider using Kotlin Serialization, which uses code generation instead of reflection. This avoids Gson's runtime crashes when optimizations are applied (usually due to the fields missing or being obfuscated), and results in faster performance on Android devices. If you still want to use Gson and attempt to avoid these crashes, you can see how to do so here.

Goals

Download

Gradle:

dependencies {
  implementation 'com.google.code.gson:gson:2.14.0'
}

Maven:

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

Gson jar downloads are available from Maven Central.

Build Status

Requirements

Minimum Java version

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.

Minimum Android API level

Older Gson versions may also support lower API levels, however this has not been verified.

Documentation

Please use the 'gson' tag on StackOverflow, GitHub Discussions or the google-gson Google group to discuss Gson or to post questions.

ProGuard / R8

See the details in the related section in the Troubleshooting guide.

Building

Gson uses Maven to build the project:

mvn clean verify

JDK 17 or newer is required for building, JDK 21 is recommended. JDK 25 is supported, but only runs a subset of all tests if JDK jmod files are missing. 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.

gson (google/gson)

Searching Database…

24.2K ·GitHub
Что это такое?Gson — это библиотека для Java, которая превращает Java-объекты в JSON и наоборот, разбирает JSON обратно в Java-объекты. Работает с любыми классами — даже с теми, для которых у вас нет исходного кода.
Чем она отличается от других Java-библиотек для JSON?Большинству Java-библиотек для JSON нужны аннотации на ваших классах, и они не до конца поддерживают дженерики. Gson не нужно ни то, ни другое: он преобразует произвольные объекты, включая уже существующие классы, которые нельзя менять, и хорошо работает с дженериками.
Как подключить её к своему проекту?Добавьте артефакт com.google.gson:gson из Maven Central как зависимость для Gradle или Maven — это библиотека, а не отдельная утилита. В репозитории есть руководство пользователя с примерами и опубликованная Javadoc-документация.
Какая версия Java мне нужна?Gson 2.12.0 и новее требует Java 8; более старые версии работают вплоть до Java 7 и даже Java 6. На Java 9+ в комплекте также идёт JPMS-модуль с именем com.google.gson.
Проект ещё активно развивается?Gson находится в режиме поддержки: существующие ошибки будут исправляться, но крупных новых возможностей вряд ли стоит ждать, а предложения по новым функциям нужно сначала обсудить в issue на GitHub.
Как преобразовать объект в JSON и обратно?Два метода: gson.toJson(obj) возвращает строку JSON, а gson.fromJson(json, MyClass.class) разбирает её обратно в объект. Для отдельных типов можно также задать своё представление.
Справится ли он со сложными графами объектов и классами, которые я не контролирую?Да — это прямо заявленная цель проекта: сколь угодно сложные объекты с глубокой иерархией наследования и активным использованием дженериков, а также преобразование уже существующих объектов без возможности изменить их или добавить аннотации.
А если у моего класса нет конструктора без аргументов?На Java 9+ Gson может откатиться к sun.misc.Unsafe, чтобы создавать такие объекты, если соответствующий модуль JDK доступен, но в README предупреждают, что это доступно не везде и имеет подводные камни; отключить это можно через GsonBuilder.disableJdkUnsafe().
Gson — это официальный продукт Google?Он размещён в организации google на GitHub, но в дисклеймере README сказано, что это не официально поддерживаемый продукт Google — это open source, поддерживаемый сообществом под лицензией Apache 2.0.
What are similar projects?fastjson, auto, javapoet, butterknife, hutool, protobuf, moshi, protobuf
Creator
google
Size
23 MB
Stars
24.2K
Age
11y
Commits · 90 Days