Разбор JSON в Android с использованием библиотеки Retrofit
JSON, также известный как (JavaScript Object Notation), представляет собой формат для обмена данными с сервером. Данные, хранящиеся в формате JSON, легкие и простые в обработке. С помощью JSON мы можем получить доступ к данным в виде JsonArray, JsonObject и JsonStringer. В этой статье мы специально рассмотрим реализацию JsonObject с использованием библиотеки Retrofit в Android.
Note: To parse JSON object in android using Voley library please refer to JSON Parsing in Android using Volley Library
JSON Object: Json Object can be easily identified with “{” braces opening and “}” braces closing. We can fetch data from JSON objects with their key value. From that key, we can access the value of that key.
Что мы собираемся построить в этой статье?
Мы будем создавать простое приложение, в котором мы будем отображать простой CardView, в котором мы будем отображать один курс, доступный на Geeks for Geeks. Пример видео приведен ниже, чтобы получить представление о том, что мы собираемся делать в этой статье. Обратите внимание, что мы собираемся реализовать этот проект на языке Java .
Ниже приведен объект JSON, из которого мы будем отображать данные в нашем приложении для Android.
{
“courseName”:”Fork CPP”,
“courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/fork-cpp-thumbnail.png”,
“courseMode”:”Online Batch”,
“courseTracks”:”6 Tracks”
}
Пошаговая реализация
Шаг 1: Создайте новый проект
Чтобы создать новый проект в Android Studio, обратитесь к разделу «Как создать/запустить новый проект в Android Studio». Обратите внимание, что в качестве языка программирования выберите Java .
Шаг 2. Добавьте приведенную ниже зависимость в файл build.gradle.
Ниже приведена зависимость для Volley, которую мы будем использовать для получения данных из API. Чтобы добавить эту зависимость, перейдите в приложение > Gradle Scripts > build.gradle(app) и добавьте приведенную ниже зависимость в раздел зависимостей. Мы использовали зависимость Picasso для загрузки изображения с URL-адреса.
// below dependency for using retrofit.
implementation ‘com.squareup.retrofit2:retrofit:2.9.0’
implementation ‘com.squareup.retrofit2:converter-gson:2.5.0’
// below dependency for using picasso image loading library
implementation ‘com.squareup.picasso:picasso:2.71828’
После добавления этой зависимости синхронизируйте свой проект и теперь переходите к части AndroidManifest.xml .
Шаг 3. Добавление разрешений в Интернет в файле AndroidManifest.xml
Перейдите к приложению > AndroidManifest.xml и добавьте в него приведенный ниже код.
XML
<!--permissions for INTERNET--><uses-permission android:name="android.permission.INTERNET"/> |
Шаг 4: Работа с файлом activity_main.xml
Перейдите к приложению > res > layout > activity_main.xml и добавьте приведенный ниже код в этот файл. Ниже приведен код файла activity_main.xml .
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <androidx.cardview.widget.CardView android:id="@+id/idCVCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:elevation="10dp" android:visibility="gone" app:cardCornerRadius="8dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/idIVCourse" android:layout_width="match_parent" android:layout_height="300dp" android:layout_margin="5dp" /> <TextView android:id="@+id/idTVCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" android:text="Course Name " android:textColor="@color/black" android:textSize="18sp" android:textStyle="bold" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal" android:weightSum="2"> <TextView android:id="@+id/idTVBatch" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:padding="5dp" android:text="Batch" android:textColor="@color/black" /> <TextView android:id="@+id/idTVTracks" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:padding="5dp" android:text="Tracks" android:textColor="@color/black" /> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <ProgressBar android:id="@+id/idLoadingPB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:visibility="visible" /> </RelativeLayout> |
Шаг 5: Создание модального класса для хранения наших данных
Перейдите к приложению> java> имя пакета вашего приложения> щелкните его правой кнопкой мыши> Создать> класс Java и назовите его как RecyclerData и добавьте к нему приведенный ниже код. Комментарии добавляются внутри кода, чтобы понять код более подробно.
Java
public class RecyclerData { // string variables for our data // make sure that the variable name // must be similar to that of key value // which we are getting from our json file. private String courseName; private String courseimg; private String courseMode; private String courseTracks; public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseimg() { return courseimg; } public void setCourseimg(String courseimg) { this.courseimg = courseimg; } public String getCourseMode() { return courseMode; } public void setCourseMode(String courseMode) { this.courseMode = courseMode; } public String getCourseTracks() { return courseTracks; } public void setCourseTracks(String courseTracks) { this.courseTracks = courseTracks; } public RecyclerData(String courseName, String courseimg, String courseMode, String courseTracks) { this.courseName = courseName; this.courseimg = courseimg; this.courseMode = courseMode; this.courseTracks = courseTracks; }} |
Шаг 6: Создание класса интерфейса для нашего вызова API
Перейдите к приложению> java> имя пакета вашего приложения> Щелкните его правой кнопкой мыши> Создать> Класс Java, выберите его как Интерфейс и назовите файл как RetrofitAPI и добавьте к нему приведенный ниже код. Комментарии добавляются внутри кода, чтобы понять код более подробно.
Java
import retrofit2.Call;import retrofit2.http.GET; public interface RetrofitAPI { // as we are making get request // so we are displaying GET as annotation. // and inside we are passing // last parameter for our url. @GET("63OH") // as we are calling data from array // so we are calling it with json object // and naming that method as getCourse(); Call<RecyclerData> getCourse();} |
Шаг 7: Работа с файлом MainActivity.java
Перейдите к файлу MainActivity.java и обратитесь к следующему коду. Ниже приведен код файла MainActivity.java . Комментарии добавляются внутри кода, чтобы понять код более подробно.
Java
import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.cardview.widget.CardView; import com.squareup.picasso.Picasso; import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { // creating variables for our textview, // imageview,cardview and progressbar. private TextView courseNameTV, courseTracksTV, courseBatchTV; private ImageView courseIV; private ProgressBar loadingPB; private CardView courseCV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. loadingPB = findViewById(R.id.idLoadingPB); courseCV = findViewById(R.id.idCVCourse); courseNameTV = findViewById(R.id.idTVCourseName); courseTracksTV = findViewById(R.id.idTVTracks); courseBatchTV = findViewById(R.id.idTVBatch); courseIV = findViewById(R.id.idIVCourse); getCourse(); } private void getCourse() { // on below line we are creating a retrofit // builder and passing our base url Retrofit retrofit = new Retrofit.Builder() // on below line we are calling add Converter // factory as GSON converter factory. .addConverterFactory(GsonConverterFactory.create()) // at last we are building our retrofit builder. .build(); // below line is to create an instance for our retrofit api class. RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class); Call<RecyclerData> call = retrofitAPI.getCourse(); call.enqueue(new Callback<RecyclerData>() { @Override public void onResponse(Call<RecyclerData> call, Response<RecyclerData> response) { if (response.isSuccessful()) { // inside the on response method. // we are hiding our progress bar. loadingPB.setVisibility(View.GONE); // in below line we are making our card // view visible after we get all the data. courseCV.setVisibility(View.VISIBLE); RecyclerData modal = response.body(); // after extracting all the data we are // setting that data to all our views. courseNameTV.setText(modal.getCourseName()); courseTracksTV.setText(modal.getCourseTracks()); courseBatchTV.setText(modal.getCourseMode()); // we are using picasso to load the image from url. Picasso.get().load(modal.getCourseimg()).into(courseIV); } } @Override public void onFailure(Call<RecyclerData> call, Throwable t) { // displaying an error message in toast Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show(); } }); }} |
Теперь запустите ваше приложение и посмотрите, что выдает приложение.