Android — JSON Parser
JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it.
Android provides four different classes to manipulate JSON data. These classes are JSONArray,JSONObject,JSONStringer and JSONTokenizer.
The first step is to identify the fields in the JSON data in which you are interested in. For example. In the JSON given below we interested in getting temperature only.
JSON — Elements
An JSON file consist of many components. Here is the table defining the components of an JSON file and their description −
Sr.No | Component & description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 |
Sr.No | Method & description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 | |||||||||||||
4 | getInt(String name) This method returns the integer value specified by the key This method returns the long value specified by the key This method returns the number of name/value mappings in this object.. This method returns an array containing the string names in this object. ExampleTo experiment with this example , you can run this on an actual device or in an emulator.
Following is the content of the modified main activity file src/MainActivity.java. Following is the modified content of the xml HttpHandler.java. Following is the modified content of the xml res/layout/activity_main.xml. Following is the modified content of the xml res/layout/list_item.xml. Following is the content of AndroidManifest.xml file. Let’s try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project’s activity files and click Run Above Example showing the data from string json,The data has contained employer details as well as salary information. Источник Учебник по JSON для Android: создание и анализ данных JSONВ этом руководстве описывается, как использовать JSON с Android . JSON расшифровывается как (Java Script Object Notation). Это простой и легкий формат обмена данными, который может быть легко прочитан людьми и машинами. JSON — это текстовый формат, не зависящий от языка. Он представляет данные в текстовом формате, чтобы их можно было легко проанализировать. Введение в JSONJSON использует две разные структуры:
Первую структуру можно использовать для моделирования объекта, поскольку объект представляет собой набор атрибутов, которые содержат некоторые значения. Массив может использоваться для моделирования списка, массива объектов и так далее. Таким образом, используя эти две структуры, мы можем передавать данные между двумя машинами простым и эффективным способом. В последнее время JSON пользуется большим успехом, и большинство доступных API поддерживает формат JSON. Давайте посмотрим, как мы можем представлять данные в формате JSON. Объект в JSON моделируется с помощью , а его атрибуты можно моделировать с помощью name: value pair.Value, в свою очередь, может быть объектом, массивом или «простым» значением, например, примитивным значением (int, Строка, логическое значение и т. Д.). Так что если у нас есть, например, класс Java, как: Источник |