📜  使用Volley Library在Android中进行JSON解析

📅  最后修改于: 2021-05-09 17:24:48             🧑  作者: Mango

JSON也称为(JavaScript Object Notation),它是一种用于交换来自服务器的数据的格式。以JSON格式存储的数据是轻量级的,并且易于处理。借助JSON,我们可以以JsonArray,JsonObject和JsonStringer的形式访问数据。在本文中,我们将专门研究在Android中使用Volley实现JsonObject的方法。

我们将在本文中构建什么?

我们将构建一个简单的应用程序,其中将显示一个简单的CardView,其中将显示Geeks for Geeks上可用的单个课程。下面提供了一个示例视频,以使您对我们在本文中将要做的事情有个大概的了解。注意,我们将使用Java语言实现该项目。

下面是JSON对象,我们将在该JSON对象中显示Android应用程序中的数据。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:在您的build.gradle文件中添加以下依赖项

以下是Volley的依赖关系,我们将使用它们来从API获取数据。要添加此依赖关系,请导航至应用程序> Gradle脚本> build.gradle(app),然后在“依赖关系”部分添加以下依赖关系。我们已将Picasso依赖项用于从URL加载图像。

添加此依赖项后,同步您的项目,现在移至AndroidManifest.xml部分。

步骤3:在AndroidManifest.xml文件中向Internet添加权限

导航至应用程序> AndroidManifest.xml,然后将以下代码添加到其中。

XML


XML


  
    
  
        
  
            
  
            
  
            
  
                
  
                
                
            
            
        
        
    
  
    
      


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.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
  
import org.json.JSONException;
import org.json.JSONObject;
  
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;
      
    // below line is the variable for url from 
    // where we will be querying our data.
    String url = "https://jsonkeeper.com/b/63OH";
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // in below line we are initializing our all views.
        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);
          
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
          
        // as our data is in json object format so we are using 
        // json object request to make data request from our url.
        // in below line we are making a json object 
        // request and creating a new json object request.
        // inside our json object request we are calling a 
        // method to get the data, "url" from where we are 
        // calling our data,"null" as we are not passing any data.
        // later on we are calling response listener method
        // to get the response from our API.
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONObject response) {
                // 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);
                try {
                    // now we get our response from API in json object format.
                    // in below line we are extracting a string with its key 
                    // value from our json object.
                    // similarly we are extracting all the strings from our json object.
                    String courseName = response.getString("courseName");
                    String courseTracks = response.getString("courseTracks");
                    String courseMode = response.getString("courseMode");
                    String courseImageURL = response.getString("courseimg");
                      
                    // after extracting all the data we are
                    // setting that data to all our views.
                    courseNameTV.setText(courseName);
                    courseTracksTV.setText(courseTracks);
                    courseBatchTV.setText(courseMode);
                      
                    // we are using picasso to load the image from url.
                    Picasso.get().load(courseImageURL).into(courseIV);
                } catch (JSONException e) {
                    // if we do not extract data from json object properly.
                    // below line of code is use to handle json exception
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            // this is the error listener method which
            // we will call if we get any error from API.
            @Override
            public void onErrorResponse(VolleyError error) {
                // below line is use to display a toast message along with our error.
                Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show();
            }
        });
        // at last we are adding our json 
        // object request to our request 
        // queue to fetch all the json data.
        queue.add(jsonObjectRequest);
    }
}


步骤4:使用activity_main.xml文件

导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。

XML格式



  
    
  
        
  
            
  
            
  
            
  
                
  
                
                
            
            
        
        
    
  
    
      

步骤5:使用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.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
  
import org.json.JSONException;
import org.json.JSONObject;
  
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;
      
    // below line is the variable for url from 
    // where we will be querying our data.
    String url = "https://jsonkeeper.com/b/63OH";
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // in below line we are initializing our all views.
        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);
          
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
          
        // as our data is in json object format so we are using 
        // json object request to make data request from our url.
        // in below line we are making a json object 
        // request and creating a new json object request.
        // inside our json object request we are calling a 
        // method to get the data, "url" from where we are 
        // calling our data,"null" as we are not passing any data.
        // later on we are calling response listener method
        // to get the response from our API.
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONObject response) {
                // 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);
                try {
                    // now we get our response from API in json object format.
                    // in below line we are extracting a string with its key 
                    // value from our json object.
                    // similarly we are extracting all the strings from our json object.
                    String courseName = response.getString("courseName");
                    String courseTracks = response.getString("courseTracks");
                    String courseMode = response.getString("courseMode");
                    String courseImageURL = response.getString("courseimg");
                      
                    // after extracting all the data we are
                    // setting that data to all our views.
                    courseNameTV.setText(courseName);
                    courseTracksTV.setText(courseTracks);
                    courseBatchTV.setText(courseMode);
                      
                    // we are using picasso to load the image from url.
                    Picasso.get().load(courseImageURL).into(courseIV);
                } catch (JSONException e) {
                    // if we do not extract data from json object properly.
                    // below line of code is use to handle json exception
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            // this is the error listener method which
            // we will call if we get any error from API.
            @Override
            public void onErrorResponse(VolleyError error) {
                // below line is use to display a toast message along with our error.
                Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show();
            }
        });
        // at last we are adding our json 
        // object request to our request 
        // queue to fetch all the json data.
        queue.add(jsonObjectRequest);
    }
}

现在运行您的应用程序,并查看该应用程序的输出。

输出:

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!