JSON也称为(JavaScript Object Notation),它是一种用于交换来自服务器的数据的格式。以JSON格式存储的数据是轻量级的,并且易于处理。借助JSON,我们可以以JsonArray,JsonObject和JsonStringer的形式访问数据。在本文中,我们将专门研究如何使用Android中的Retrofit库实现JsonObject。
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对象,我们将在该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脚本> build.gradle(app),然后在“依赖关系”部分添加以下依赖关系。我们已将Picasso依赖项用于从URL加载图像。
// below dependancy for using retrofit.
implementation ‘com.squareup.retrofit2:retrofit:2.9.0’
implementation ‘com.squareup.retrofit2:converter-gson:2.5.0’
// below dependancy for using picasso image loading library
implementation ‘com.squareup.picasso:picasso:2.71828’
添加此依赖项后,同步您的项目,现在移至AndroidManifest.xml部分。
步骤3:在AndroidManifest.xml文件中向Internet添加权限
导航至应用程序> AndroidManifest.xml,然后将以下代码添加到其中。
XML
XML
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;
}
}
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 getCourse();
}
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()
.baseUrl("https://jsonkeeper.com/b/")
// 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 call = retrofitAPI.getCourse();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response 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 call, Throwable t) {
// displaying an error message in toast
Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show();
}
});
}
}
步骤4:使用activity_main.xml文件
导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。
XML格式
第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类,将其选择为Interface并将文件命名为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 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()
.baseUrl("https://jsonkeeper.com/b/")
// 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 call = retrofitAPI.getCourse();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response 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 call, Throwable t) {
// displaying an error message in toast
Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show();
}
});
}
}
现在运行您的应用程序,并查看该应用程序的输出。