首先你必须使用添加 volley 库
编译'com.mcxiaoke.volley:library-aar:1.0.0'
在如下所示的 build.grdle 文件中
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "com.iitism.ritik.popularmovies"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:design:24.1.1'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile files('libs/YouTubeAndroidPlayerApi.jar')
}
然后你需要一个 url 来获取 json 对象
之后你可以按照下面的代码来解析 json
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("TAG",response);
showJson(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
public void showJson(String response)
{
Log.d("TAG",response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("results");
int n = jsonArray.length();
for(int i=0;i<n;i++)
{
JSONObject movieObject = jsonArray.getJSONObject(i);
String title = movieObject.getString("original_title");
String poster_path = movieObject.getString("poster_path");
String overView = movieObject.getString("overview");
String releaseDate = movieObject.getString("release_date");
String popularity = movieObject.getString("popularity");
String voteAvg = movieObject.getString("vote_average");
String id = movieObject.getString("id");
movieList.add(new Movie(poster_path,title,overView,releaseDate,popularity,voteAvg,id));
movieAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),"Not available",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
就像在你的 json 中你想解析 "articles" 数组,所以你可以使用下面的代码
JSONArray jsonArray = jsonObject.getJSONArray("articles");
int n = jsonArray.length();
for(int i=0;i<n;i++)
{
JSONObject movieObject = jsonArray.getJSONObject(i);
//do your work here
}