admin / 16.05.2018

Json java пример

.

Обзор Gson — работаем с JSON в Java

2016-02-26 Туториалы по программированию

JSON, что означает JavaScript Object Notation, — это текстовый формат обмена данными, который легко читается человеком и в то же время является компактным (в отличии от того же XML формата).

JSON произошел от javascript и очень часто используется в веб-программировании при обмене данными между веб-браузером и сервером. В самом javascript каждый валидный json объект может быть легко десериализован с помощью встроенной функции eval().

Вообще, о самом формате JSON в Интернете написано более чем достаточно, ну а в этой статье я хочу рассмотреть бибилиотеку Gson для сериализации и десериализации java объектов в JSON. Полный код примеров из статьи, оформленных в виде тест кейсов, можно найти на GitHub по этой ссылке — GsonTest.java.

А вот что нас сегодня ожидает:

Обзор библиотеки Gson

Gson — это небольшая java библиотека, которая позволяет конвертировать java объекты в их JSON представление, равно как и создавать объекты на основании их json представления.

Изначально Gson был разработан в Google и использовался в нескольких внтуренних проектах. Через некоторое время было принято решение отдать библиотеку в open-source, чтобы она и дальше развивалась.

Основным классом библиотеки есть одноименный класс Gson. Для того, чтобы создать экземпляр класса нужно воспользоваться одним из двух способов:

  • Gson gson = new Gson();
  • Gson gson = new GsonBuilder().create();

Первый способ создаст инстанс класса с настройками по умолчанию, а второй способ позволит применить некоторые настройки. О настройках расскажу чуть ниже.

Основные методы, которые используются для сериализации и десериализации java-объектов, называются toJson и fromJson.

Сериализация и десериализация в Gson

Начнем с чего-нибудь попроще:

Gson gson = new Gson(); gson.toJson(123); // 123 gson.toJson(«hello»); // «hello» gson.toJson(Long.valueOf(10)); // 10

Это так называемы примитивы JSON. А вот так их можно десериализовать:

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); // {«id»:100,»name»:»name»} Entity read = gson.fromJson(json, Entity.class); System.out.println(read.random); // 0

Обратите внимание, что при сериализации значение поля random не было сохранено. Все дело в том, что поведение библиотеки по-умолчанию не сериализует поля, помеченные модификатором transient. О том, как изменить это поведение, читайте в разделе про GsonBuilder.

Работа с коллекциями

Сериализация коллекций, таких как ArrayList, LinkedList, HashSet, TreeMap и других, реализована таким образом:

  • метод toJson для Collection вернет массив объектов или примитивов;
  • метод toJson для Map вернет ассоциативный массив.

С десериализацией все немного сложнее. Рассмотрим следующий пример:

Map<String, Integer> map = new LinkedHashMap<>(); map.put(«USD», 123); map.put(«EUR», 321); String json = gson.toJson(map); Type type = new TypeToken<Map<String, Integer>>(){}.getType(); Map<String, Integer> read = gson.fromJson(json, type);

Обратите внимание как мы определили тип для коллекции при десериализации. К сожалению, сделать это как-то проще не получится, c’est la vie…

Допустим, вам необходимо конвертировать коллекцию, содержащую объекты различных типов. В этом случае с сериализацией проблем не возникнет, например:

Collection collection = new ArrayList(); collection.add(«string»); collection.add(10); collection.add(new Entity(11, «text»)); gson.toJson(collection); // [«string»,10,{«id»:11,»name»:»text»}]

А вот десереализовать такую коллекцию не получится, так как Gson не сможет найти правильные соответствия для типов данных.

Одним из самых хороших решений этой проблемы будет использование низкоуровневого API — классы JsonElement, JsonPrimitive, JsonObject и так далее.

Пример работы с Json Simple в Java: парсинг и создание JSON

Некоторое представление о том, как это сделать, вы сможете получить в следующем разделе статьи.

Определяем свои правила конвертации объектов

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<Custom>, JsonDeserializer<Custom> { 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();

Настройки Gson и класс GsonBuilder

В этом разделе я бы хотел мельком рассмотреть несколько настроек класса GsonBuilder.

По умолчанию результат сериализации в json будет компактным, то есть все лишние whitespace символы будут удалены.

Это позволит, например, уменьшить траффик при передачи JSON объектов по сети.

Метод setPrettyPrinting у класса GsonBuilder меняет это поведение и сериализует объекты в удобную для человека форму с пробелами и переводами строк. Пример вы можете посмотреть по ссылке приведенной в начале статьи.

Еще одна полезная настройка для GsonBuilder — excludeFieldsWithModifiers. Она позволяет изменить набор несериализуемых полей при конвертации java объектов в JSON. По умолчанию игнорируются только поля с модификатором transient.

Ну вот наверное и все. Вопросы и комментарии приветствуются.

Parsing JSON in Java


A lot of APIs will give you responses in JSON format. Here we’ll review JSON parsing in Java so that you can get to the interesting data faster.

This tutorial assumes that you’ve already gone through our Java getting started tutorial and are familiar with how our Java SDK works. Although we use the output from our YouTube ListSearchResults Choreo in this tutorial, the same steps we outline here will work for parsing any JSON in Java.

Get JSON output

1Log in to Temboo and go to the YouTube > Search > ListSearchResults Choreo in our Library.

2 Enter any search term you want for the Query input and click Generate Code to test the Choreo from our website.

3 You get a whole bunch of JSON in the Response output. These are the results of the search. Next we’ll see how to parse through this response in Java and pick out only the pieces we’re interested in.

Parse it in Java

4 Create a new Java class and copy in the code below. In steps 5-8, we’ll go over what happens in the code.

import org.json.JSONArray; import org.json.JSONObject; import com.temboo.Library.YouTube.Search.ListSearchResults; import com.temboo.Library.YouTube.Search.ListSearchResults.ListSearchResultsInputSet; import com.temboo.Library.YouTube.Search.ListSearchResults.ListSearchResultsResultSet; import com.temboo.core.TembooSession; public class SearchVideos { public static void main(String[] args) throws Exception { // Create a new Temboo session. TembooSession session = new TembooSession(«ACCOUNT_NAME», «APP_NAME», «APP_KEY»); // Instantiate the YouTube.Search.ListSearchResults Choreo, using the session object. ListSearchResults listSearchResultsChoreo = new ListSearchResults(session); // Get an InputSet object ListSearchResultsInputSet listSearchResultsInputs = listSearchResultsChoreo.newInputSet(); // Set inputs listSearchResultsInputs.set_Query(«quantum entanglement»); // Execute choreo ListSearchResultsResultSet listSearchResultsResults = listSearchResultsChoreo.execute(listSearchResultsInputs); // Parse JSON response using org.json JSONObject results = new JSONObject(listSearchResultsResults.get_Response()); // Get items array JSONArray items = results.getJSONArray(«items»); // Get first item JSONObject item = items.getJSONObject(0); // Get the snippet object within the first item JSONObject snippet = item.getJSONObject(«snippet»); // Parse the title and description fields String title = snippet.getString(«title»); String description = snippet.getString(«description»); // Print title and description System.out.println(title); System.out.println(description); } }

5First we converted the JSON text from the response to a Java Object using a constructor.

6 Next, we parsed out the piece of data we want from the JSON. It helps to look at the JSON file’s structure to get an idea of how it is organized. The two main elements you should look for are:

Class name How it appears in the JSON file
JSONArray «name»: [
JSONObject «name»: {

For these results, we wanted the title of the first video in the search results.

Урок 14. Знакомство с форматом JSON. Парсинг JsonObject на примере объекта User

We got the items array, then the first item in that array (at index 0). Then we wanted the snippet object within the first item in the array. We used the and methods for this. In other words:

Method name Description
getJSONArray(«items») The array of videos in the search results
getJSONObject(0) The first video within those results
getJSONObject(«snippet») The snippet containing descriptive details of each video

7 To finish up, we parsed the title property from the snippet object using the method.

8All finished! Run the code in your Java IDE to try it out. You should see the title of your first YouTube Search result in the console.

What next?

Now you should be to able to parse all sorts of JSON responses with our Java SDK. Check out the 2000+ Choreos in our Library and find some exciting data to parse.

Once you’ve got your code up and running, you’re ready to move on and do more. From monitoring your running applications, to moving your generated Temboo code to your preferred development environment and sharing it with colleagues, collaborators and friends — we’ve got you covered.

Need help?

We’re always happy to help. Just email us at support@temboo.com, and we’ll answer your questions.


Back

Commit Code to GitHub

Commit Temboo-generated code directly to GitHub and share with the world. Learn more.

Introducing JSON


العربيةБългарски中文ČeskýDanskNederlandsEnglishEsperantoFrançaisDeutschΕλληνικάעבריתMagyarIndonesia
Italiano日本한국어فارسیPolskiPortuguêsRomânăРусскийСрпско-хрватскиSlovenščinaEspañolSvenskaTürkçeTiếng Việt


ECMA-404 The JSON Data Interchange Standard.


object
members
members
pair
pairmembers
pair
stringvalue
array
elements
elements
value
valueelements
value
string
number
object
array


string
chars
chars
char
char chars
char
any-Unicode-character-
    except--or--or-
    control-character

four-hex-digits

number
int
int frac
int exp
int frac exp
int
digit
digit1-9 digits
digit
digit1-9 digits
frac
digits
exp
edigits
digits
digit
digitdigits
e

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition — December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.

In JSON, they take on these forms:

An object is an unordered set of name/value pairs. An object begins with  (left brace) and ends with  (right brace). Each name is followed by  (colon) and the name/value pairs are separated by  (comma).

An array is an ordered collection of values. An array begins with  (left bracket) and ends with  (right bracket).

Пример работы с JSON.org в Java: разбор и создание JSON

Values are separated by  (comma).

A value can be a string in double quotes, or a number, or or or , or an object or an array. These structures can be nested.

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.


FILED UNDER : IT

Submit a Comment

Must be required * marked fields.

:*
:*