- How to Extract Data from JSON Array in Android using Retrofit Library?
- What we are going to build in this article?
- Step by Step Implementation
- Android — JSON Parser
- JSON — Elements
- JSON — Parsing
- Example
- Учебник по JSON для Android: создание и анализ данных JSON
- Введение в JSON
- Android — JSON Parser
- JSON — Elements
- JSON — Parsing
- Example
- Учебник по JSON для Android: создание и анализ данных JSON
- Введение в JSON
How to Extract Data from JSON Array in Android using Retrofit Library?
In the previous article on JSON Parsing in Android using Retrofit Library, we have seen how we can get the data from JSON Object in our android app and display that JSON Object in our app. In this article, we will take a look at How to extract data from JSON Array and display that in our app.
Note: To e xtract Data from JSON Array in Android using Volley Library please refer to How to Extract Data from JSON Array in Android using Volley Library?
JSON Array: JSON Array is a set or called a collection of data that holds multiple JSON Objects with similar sort of data. JSON Array can be easily identified with “[” braces opening and “]” braces closing. A JSON array is having multiple JSON objects which are having similar data. And each JSON object is having data stored in the form of key and value pair.
What we are going to build in this article?
We will be building a simple application in which we will be displaying a list of CardView in which we will display some courses which are available on Geeks for Geeks. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Below is our JSON array from which we will be displaying the data in our Android App.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add the below dependency in your build.gradle file
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL.
// below dependancy for using picasso image loading library
Источник
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, как: Источник Android — JSON ParserJSON 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 — ElementsAn JSON file consist of many components. Here is the table defining the components of an JSON file and their description −
|