- Работа с JSON на Java (библиотека GSON)
- 1 Обзор библиотеки Gson
- 1.1 Подключение GSON
- 1.2 Использование GSON
- 2 Сериализация и десериализация в Gson
- 3 Работа с коллекциями
- 4 Определяем свои правила конвертации объектов
- 5 Настройки Gson и класс GsonBuilder
- 6 Пример использования GSON
- Saved searches
- Use saved searches to filter your results more quickly
- License
- google/gson
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
Работа с JSON на Java (библиотека GSON)
Заметка взята с сайта Javenue, так как несет много полезной информации. Спасибо ее автору.
Заметка была дополнена, поэтому если обнаружатся неточности — прошу писать мне. JSON, что означает JavaScript Object Notation, — это текстовый формат обмена данными, который легко читается человеком и в то же время является компактным (в отличии от того же XML формата). По сути это набор пар “ключ-значение”, объединенных в последовательность значений(массив). Допустим мы производим выборку информацию о заказчике из БД и возвращаем сведения о нем. Пример строки в формате JSON будет выглядеть так: Вообще, о самом формате JSON в Интернете написано более чем достаточно, ну а в этой статье я хочу рассмотреть бибилиотеку Gson для сериализации и десериализации java объектов в JSON.
1 Обзор библиотеки Gson
Gson — это небольшая java библиотека, которая позволяет конвертировать java объекты в их JSON представление, равно как и создавать объекты на основании их json представления. Изначально Gson был разработан в Google и использовался в нескольких внтуренних проектах. Через некоторое время было принято решение отдать библиотеку в open-source, чтобы она и дальше развивалась.
1.1 Подключение GSON
Сначала подключим библиотеку. Если вы используете в качестве сборщика Gradle, добавьте новую зависимость: compile ‘com.google.code.gson:gson:2.4’ Вот, что нужно прописать в файл pom.xml тем, кто использует Maven:
com.google.code.gson gson 2.8.0
1.2 Использование GSON
Основным классом библиотеки есть одноименный класс Gson. Для того, чтобы создать экземпляр класса нужно воспользоваться одним из двух способов:
Gson gson = new Gson(); Gson gson = new GsonBuilder().create();
Первый способ создаст инстанс класса с настройками по умолчанию, а второй способ позволит применить некоторые настройки. О настройках расскажу чуть ниже. Основные методы, которые используются для сериализации и десериализации java-объектов, называются toJson и fromJson .
2 Сериализация и десериализация в Gson
Gson gson = new Gson(); gson.toJson(123); // 123 gson.toJson("hello"); // "hello" gson.toJson(Long.valueOf(10)); // 10
Integer integer = gson.fromJson("1", int.class); String string = gson.fromJson("\"world\"", String.class); Boolean bool = gson.fromJson("true", Boolean.class);
Так как инстанс Gson не имеет внутреннего состояния, то его можно переиспользовать произвольное количество раз, а так же использовать в многопоточных приложениях. Идем дальше. Вот таким образом можно сериализовать и десеарелизовать массив:
String string = gson.toJson(new int[] < 10, 100 >); // [10,100] int[] array = gson.fromJson("[10,100]", int[].class)
С объектами, которые в качестве полей содержат строки и примитивы, все тоже достаточно просто. Допустим, у нас в приложении описан следующий класс:
public static class Entity < volatile int id; String name; transient long random; public Entity(int id, String name) < this.id = id; this.name = name; >>
Entity entity = new Entity(100, "name"); entity.random = 1234;
String json = gson.toJson(entity); // Entity read = gson.fromJson(json, Entity.class); System.out.println(read.random); // 0
Обратите внимание, что при сериализации значение поля random не было сохранено. Все дело в том, что поведение библиотеки по-умолчанию не сериализует поля, помеченные модификатором transient . О том, как изменить это поведение, читайте в разделе про GsonBuilder .
3 Работа с коллекциями
- метод toJson для Collection вернет массив объектов или примитивов;
- метод toJson для Map вернет ассоциативный массив.
С десериализацией все немного сложнее. Рассмотрим следующий пример:
Map map = new LinkedHashMap<>(); map.put("USD", 123); map.put("EUR", 321); String json = gson.toJson(map); Type type = new TypeToken
Обратите внимание как мы определили тип для коллекции при десериализации. К сожалению, сделать это как-то проще не получится.
Допустим, вам необходимо конвертировать коллекцию, содержащую объекты различных типов. В этом случае с сериализацией проблем не возникнет, например:
Collection collection = new ArrayList(); collection.add("string"); collection.add(10); collection.add(new Entity(11, "text")); gson.toJson(collection); // ["string",10,]
А вот десереализовать такую коллекцию не получится, так как Gson не сможет найти правильные соответствия для типов данных.
Одним из самых хороших решений этой проблемы будет использование низкоуровневого API — классы JsonElement, JsonPrimitive, JsonObject и так далее. Некоторое представление о том, как это сделать, вы сможете получить в следующем разделе статьи.
4 Определяем свои правила конвертации объектов
Gson позволяет разработчикам определять свои собственные правила для сериализации и десериализации объектов. Зарегистрировать их можно с помощью метода registerTypeAdapter() .
Допустим, у нас в приложении есть следующий класс:
public static class Custom < Date date; BigInteger integer; public Custom(Date date, BigInteger integer) < this.date = date; this.integer = integer; >>
Для кастомного сериализатора необходимо реализовать интерфейс JsonSerializer , а для десериализаторв — соответственно JsonDeserializer . Для простоты можно создать один класс, который реализует оба эти интерфейса:
public class CustomConverter implements JsonSerializer, JsonDeserializer < public JsonElement serialize(Custom src, Type type, JsonSerializationContext context) < JsonObject object = new JsonObject(); object.addProperty("date", src.date.getTime()); object.addProperty("integer", src.integer.toString()); return object; >public Custom deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException < JsonObject object = json.getAsJsonObject(); Date date = new Date(object.get("date").getAsLong()); BigInteger integer = new BigInteger(object.get("integer").getAsString()); return new Custom(date, integer); >>
Зарегистрировать наш класс можно следующим образом:
GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Custom.class, new CustomConverter()); Gson gson = builder.create();
5 Настройки Gson и класс GsonBuilder
По умолчанию результат сериализации в json будет компактным, то есть все лишние whitespace символы будут удалены. Это позволит, например, уменьшить траффик при передачи JSON объектов по сети.
Метод setPrettyPrinting у класса GsonBuilder меняет это поведение и сериализует объекты в удобную для человека форму с пробелами и переводами строк. Пример вы можете посмотреть по ссылке приведенной в начале статьи.
Еще одна полезная настройка для GsonBuilder — excludeFieldsWithModifiers . Она позволяет изменить набор несериализуемых полей при конвертации java объектов в JSON. По умолчанию игнорируются только поля с модификатором transient .
6 Пример использования GSON
Нам надо преобразовать данные JSON в Java-объект. Пусть у нас имеется класс Student , представляющий заказчика, с определенными полями: имя и курс.
public class Student < @SerializedName("name") private String name; @SerialazedName("course") private int course; public Student() < >public Student(String name, int course) < this.name = name; this.course = age; >public String getName() < return name; >public void setName(String name) < this.name = name; >public int getCourse() < return course; >public void setCourse(int course) < this.course = course; >>
Аннотация @SerializedName используется для изменения выходного имени свойства при сериализации, если это потребуется.
Итак, мы получили объект в виде строки, например такой объект может прийти приложению-клюиенту от сервера или может быть считан с файла. Для выполнения парсинга нам необходимо получить объект класса Gson , для этого удобно использовать GsonBuilder . Преобразование JSON в объект класса Student выполняется методом Gson.from() :
import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class Example < public static void main(String[] args) < String str = ""; GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); Student student = gson.fromJson(str, Student.class); System.out.println("Имя: " + student.getName() + "\nКурс: " + student.getCourse()); > >
Например, можно считывать объекты из файла по одному. Однако, если у вас есть корректный JSON файл или сервер прислал сразу массив объектов — то их можно сразу преобразовать в массив. Например, при запросе истории погоды или курса валют за период сервер мог бы прислать вам массив однотипных объектов.
Type collectionType = new TypeToken>()<>.getType(); Collection = gson.fromJson(response, collectionType);
Здесь методу fromJson() мы в качестве второго параметра должны передаем тип нашей коллекции.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A Java serialization/deserialization library to convert Java Objects into JSON and back
License
google/gson
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
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.
ℹ️ 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.
- Provide simple toJson() and fromJson() 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)
dependencies < implementation 'com.google.code.gson:gson:2.10.1' >
dependency> groupId>com.google.code.gsongroupId> artifactId>gsonartifactId> version>2.10.1version> dependency>
Gson jar downloads are available from Maven Central.
Despite supporting older Java versions, Gson also provides a JPMS module descriptor (module name com.google.gson ) for users of Java 9 or newer.
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 class sun.misc.Unsafe (optional)
When this module is present, Gson can use the Unsafe 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, see GsonBuilder.disableJdkUnsafe() .
Minimum Android API level
Older Gson versions may also support lower API levels, however this has not been verified.
- 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 or the google-gson Google group to discuss Gson or to post questions.
Related Content Created by Third Parties
Gson uses Maven to build the project:
JDK 11 or newer is required for building, JDK 17 is recommended.
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.
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.
This is not an officially supported Google product.
About
A Java serialization/deserialization library to convert Java Objects into JSON and back