Json обработка в java

Java API for JSON Processing: An Introduction to JSON

JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types.

Listing 1 is an example from Wikipedia that shows the JSON representation of an object that describes a person. The object has string values for first name and last name, a number value for age, an object value representing the person’s address, and an array value of phone number objects.

Listing 1. Example of JSON representation of an object

JSON is often used in Ajax applications, configurations, databases, and RESTful web services. All popular websites offer JSON as the data exchange format with their RESTful web services.

JSON Processing

The Java API for JSON Processing (JSR 353) provides portable APIs to parse, generate, transform, and query JSON using object model and streaming APIs.

The object model API creates a random-access, tree-like structure that represents the JSON data in memory. The tree can then be navigated and queried. This programming model is the most flexible and enables processing that requires random access to the complete contents of the tree. However, it is often not as efficient as the streaming model and requires more memory.

The streaming API provides a way to parse and generate JSON in a streaming fashion. It hands over parsing and generation control to the programmer. The streaming API provides an event-based parser and allows an application developer to ask for the next event rather than handling the event in a callback. This gives a developer more procedural control over the JSON processing. Application code can process or discard the parser event and ask for the next event (pull the event). The streaming model is adequate for local processing where random access of other parts of the data is not required. Similarly, the streaming API provides a way to generate well-formed JSON to a stream by writing one event at a time.

The Object Model API

The object model API is similar to the Document Object Model (DOM) API for XML. It is a high-level API that provides immutable object models for JSON object and array structures. These JSON structures are represented as object models using the Java types JsonObject and JsonArray. Table 1 lists the main classes and interfaces in the object model API.

JsonObject provides a Map view to access the unordered collection of zero or more name/value pairs from the model. Similarly, JsonArray provides a List view to access the ordered sequence of zero or more values from the model.

  • JsonObjectBuilder
  • JsonArrayBuilder
  • JsonValue
  • JsonObject
  • JsonArray
  • JsonString
  • JsonNumber
Читайте также:  Advanced project in php

JsonObject , JsonArray , JsonString , and JsonNumber are subtypes of JsonValue . These are constants defined in the API for null, true, and false JSON values.

The object model API uses builder patterns to create these object models from scratch. Application code can use the interface JsonObjectBuilder to create models that represent JSON objects. The resulting model is of type JsonObject . Application code can use the interface JsonArrayBuilder to create models that represent JSON arrays. The resulting model is of type JsonArray .

These object models can also be created from an input source (such as InputStream or Reader ) using the interface JsonReader . Similarly, these object models can be written to an output source (such as OutputStream or Writer ) using the class JsonWriter .

For example, let’s write code to search Facebook’s public posts using the object model API. The Facebook API gives the search results in the JSON format shown in Listing 2:

 < "data" : [ < "from" : < "name" : "xxx", . >, "message" : "yyy", . >, < "from" : < "name" : "ppp", . >, "message" : "qqq", . >, . ], . > 

Listing 2. JSON representation of searching Facebook public posts

We can use the object model API to get names and their public posts about the term java. In the Listing 3, lines 1 through 3 lines create JsonReader ; line 5 creates JsonObject for the results; line 7 loops over each result; and lines 8 through 11 get the name of the person who posted, get the public post, and prints them. Note that the JsonReader and other objects in this API can be used in the try -with-resources statement (which is also called automatic resource management [ARM]).

 URL url = new URL("https://graph.facebook.com/search?q=java&type=post"); try (InputStream is = url.openStream(); JsonReader rdr = Json.createReader(is)) < JsonObject obj = rdr.readObject(); JsonArray results = obj.getJsonArray("data"); for (JsonObject result : results.getValuesAs(JsonObject.class)) < System.out.print(result.getJsonObject("from").getString("name")); System.out.print(": "); System.out.println(result.getString("message", "")); System.out.println("-----------"); >> 

Listing 3. Processing Facebook posts using the object model API

The Streaming API

The streaming API is similar to the Streaming API for XML (StAX) and consists of the interfaces JsonParser and JsonGenerator. JsonParser contains methods to parse JSON data using the streaming model. JsonGenerator contains methods to write JSON data to an output source. Table 2 lists the main classes and interfaces in the streaming API.

Class or Interface Description
Json Contains static methods to create JSON parsers, generators, and their factory objects.
JsonParser Represents an event-based parser that can read JSON data from a stream.
JsonGenerator Writes JSON data to a stream one value at a time

JsonParser provides forward, read-only access to JSON data using the pull parsing programming model. In this model, the application code controls the thread and calls methods in the parser interface to move the parser forward or to obtain JSON data from the current state of the parser.

JsonGenerator provides methods to write JSON data to a stream. The generator can be used to write name/value pairs in JSON objects and values in JSON arrays.

The streaming API is a low-level API designed to process large amounts of JSON data efficiently. Other JSON frameworks (such as JSON binding) can be implemented using this API.

Let’s use the streaming API to do the same thing that was done with the object model API, that is, to search Facebook’s public posts about java. In Listing 4, lines 1 through 3 create a streaming parser, lines 4 through 5 get the next event, line 6 looks for the KEY_NAME event, lines 8 through 11 read names and print them, and lines 14 through 16 read the public posts and print them. The use of streaming API provides an efficient way to access names and their public posts when compared to the same task using the object model API.

 URL url = new URL("https://graph.facebook.com/search?q=java&type=post"); try (InputStream is = url.openStream(); JsonParser parser = Json.createParser(is)) < while (parser.hasNext()) < Event e = parser.next(); if (e == Event.KEY_NAME) < switch (parser.getString()) < case "name": parser.next(); System.out.print(parser.getString()); System.out.print(": "); break; case "message": parser.next(); System.out.println(parser.getString()); System.out.println("---------"); break; >> > > 

Listing 4. Processing Facebook posts using the streaming API

Читайте также:  Where php ini located

Conclusion

The Java API for JSON Processing provides the following capabilities:

  • Parsing input streams into immutable objects or event streams
  • Writing event streams or immutable objects to output streams
  • Programmatically navigating immutable objects
  • Programmatically building immutable objects with builders

The API becomes a base for building data binding, transformation, querying, or other manipulation APIs. JAX-RS 2.0 provides native integration for the Java API for JSON Processing.

See Also

About the Author

Jitendra Kotamraju, a principal member of the technical staff at Oracle, is the JSON Processing specification lead and one of the key engineers behind GlassFish. Before leading the JSON Processing project, he was in charge of both the specification and implementation of JAX-WS 2.2.

Источник

Кофе-брейк #175. Как мы можем прочитать файл JSON в Java? Что такое Java Development Kit (JDK)?

Java-университет

Кофе-брейк #175. Как мы можем прочитать файл JSON в Java? Что такое Java Development Kit (JDK)? - 1

Источник: DZone JSON — это простой формат для хранения и отправки данных на веб-страницу. Обычно он используется в JavaScript, но сегодня мы узнаем, как с ним работать в Java.

Чтение файла JSON в Java

  • JSON — это текстовый файл, поэтому его можно легко передавать.
  • JSON не зависит от конкретного языка.

Синтаксис

Данные в файле JSON должны быть в формате пар имя/значение, запятыми разделяют различные данные. Фигурные скобки используются для хранения объектов, а квадратные скобки — для хранения массивов.

Особенности JSON

  • Простой.
  • Имеет независимую платформу.
  • Легко передать.
  • Поддерживает расширяемость.
  • Наличие совместимости.

Типы данных

  • String — строка представлена ​​внутри кавычек.
  • Number — представляет числовые символы.
  • Boolean – состоит либо из true, либо из false.
  • Null – пустой.

JSON в Java

JSON-объекты

JSON-объекты представлены между фигурными скобками. Объекты должны быть в парах ключ/значение (key/value). Ключ представлен в виде String, а значения представляют любые типы данных, упомянутые выше. Пример:

JSON-массивы

Массивы JSON используются для хранения объектов. Эти объекты заключены в квадратные скобки []. Пример:

В приведенном выше примере сведения о студентах представлены в виде массива, а внутри массива данные о студентах хранятся в виде объектов.

Простая программа для JSON на Java

 import org.json.simple.JSONObject; public class Json < public static void main(String args[]) < JSONObject j = new JSONObject(); j.put("Name", "Kotte"); j.put("College", "BVRIT"); j.put("Branch" , "Computer science engineering"); j.put("Section", "CSE-C"); System.out.println(j); >> 

Чтение файла JSON в Java

Приведенный выше код — это файл, который используется для чтения. Мы используем библиотеку json.simple .

 //program for reading a JSON file import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.*; public class JSON < public static void main(Strings args[]) < // file name is File.json Object o = new JSONParser().parse(new FileReader(File.json)); JSONObject j = (JSONObject) o; String Name = (String) j.get("Name"); String College = (String ) j.get("College"); System.out.println("Name :" + Name); System.out.println("College :" +College); >> 

В данной программе используется JSONParser().parse() , который присутствует в org.json.simple.parser.* для анализа файла File.json.

Читайте также:  Php parse url пример

Что такое Java Development Kit (JDK)?

Источник: Medium Эта публикация ознакомит вас с работой и сферой использования Java Development Kit. В своей работе программисты часто используют Java Development Kit (Комплект для разработки Java), известный как JDK. Он представляет собой кроссплатформенный набор инструментов и библиотек для создания программных приложений и апплетов на основе Java. Пакет JDK включает в себя как виртуальную машину Java (известную как JVM), так и среду выполнения Java (известную как JRE). Также в JDK имеется компилятор javac, инструменты мониторинга производительности, отладчик, стандартные библиотеки классов Java, примеры, документация и различные утилиты. Разработкой Java Development Kit (JDK) занимается корпорация Oracle. В ее продукте реализованы JVMS, JLS и Java API SE (API). Помимо коммерческой версии Oracle представила на рынке бесплатную версию пакета OpenJDK. Также на рынке Java-разработки существуют альтернативные JDK от других компаний. Если единственное, что вы хотите сделать на своем компьютере, — это запускать Java-приложения, то вам не нужно беспокоиться о различиях между Java Runtime Environment (JRE) и Java Development Kit (JDK). Однако вам понадобится Java Development Kit (JDK) для создания программного обеспечения на основе Java. Среда выполнения Java (JRE), входящая в состав JDK, называется частной средой выполнения (Private Runtime). Эта среда отличается от стандартной JRE тем, что включает дополнительные компоненты. Также она дает разработчикам доступ к виртуальной машине Java (JVM) и всем библиотекам классов, используемым в производственных средах, в дополнение к библиотекам интернационализации и IDL.

Самые популярные JDK

  • Azul Systems Zing : высокопроизводительная виртуальная машина Java с малой задержкой для Linux.
  • Azul Systems (для Linux, Windows, Mac OS X и IBM J9 JDK: для AIX, Linux, Windows и многих других операционных систем).
  • Amazon Corretto (OpenJDK и долгосрочная поддержка включены).

Скомпилируйте и запустите код Java с помощью JDK

Вы можете создать исполняемую программу Java из текстового файла с помощью компилятора JDK. При компиляции ваш Java-код преобразуется в байт-код с расширением .class . Для начала вам нужно создать текстовый файл Java и сохранить его под уникальным именем. В данном случае мы сохраняем Hello.java в качестве имени файла. Затем запустите инструмент компиляции Java командой javac , и все готово. Чтобы избежать получения сообщения об ошибке, такого как “The system cannot locate a path supplied” (Система не может найти указанный путь), вы должны указать полный путь к вашему текстовому файлу Java. Hello — это имя файла, а полному пути к файлу предшествует Hello в следующем примере команды. Путь и исполняемый файл для javac.exe должны быть заключены в кавычки. Теперь, когда Hello.class создан, вы можете увидеть его в том же каталоге, что и Hello.java , что очень удобно. Теперь вы можете выполнить свой код, просто набрав java hello в своем терминале. Имейте в виду, что запуск вашего кода не требуется включение файла .class.

Компонент Jar

В JDK включены многие важные инструменты. Помимо javac чаще всего используется инструмент jar. В нем можно найти не что иное, как набор классов Java. Как только файлы .class будут готовы, вы можете упаковать их и сохранить в архиве, известном как “jar”. После этого jar-файл можно запускать в мобильной среде (Android).

Источник

Оцените статью