使用android volley库解析JSON数组中的JSON对象

时间:2016-10-23 00:33:26

标签: android json android-volley

我有来自服务器的json响应,附在下面。我想用android中的volley来解析这个响应。如何解析数组中的对象。

  {
  "status": "ok",
  "source": "techcrunch",
  "sortBy": "top",
  "articles": [
    {
      "author": "Ingrid Lunden, Fitz Tepper",
      "title": "Confirmed: AT&T is buying Time Warner for $85.4B in cash and shares",
      "description": "After days of speculation, the deal is now official: AT&T is acquiring Time Warner for $85 billion in a mix of cash and shares, paving the way for..",
      "url": "http://social.techcrunch.com/2016/10/22/confirmed-att-is-buying-time-warner-for-85-4b-in-cash-and-shares/",
      "urlToImage": "https://tctechcrunch2011.files.wordpress.com/2016/10/946_432_newsroom_release_tw.jpg?w=764&h=400&crop=1",
      "publishedAt": "2016-10-23T00:02:34Z"
    },

我想要访问第一个对象,然后是下一个对象,然后是下一个对象。升值。

6 个答案:

答案 0 :(得分:3)

这应显示标题列表

JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, null,
    new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            JSONArray jsonArray = null;
            try {
                jsonArray = response.getJSONArray("articles");
                for(int i=0; i<jsonArray.length(); i++){
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                        Log.d(TAG, jsonObject.getString("title"));
                    }
                } catch (JSONException e) {
                        e.printStackTrace();
                }                       }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "Error: " + error.getMessage());
        }
   });

答案 1 :(得分:0)

首先你必须使用

添加排球库

编译'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中你想解析“文章”数组所以你可以使用下面的代码

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
    }

答案 2 :(得分:0)

首先检查此APi是POST API还是GET API。如果这个api是POST方法,那么在hashmap中传递参数。如果它是GET api,则传递参数和url。以下代码解析你给定的json。

     StringRequest notificationrequest = new StringRequest(Request.Method.POST, YOUR_URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {



                            try {


                                JSONObject jObject = new JSONObject(response);
                                if (jObject.getString("status").equals("ok")) {

                                String source = jObject.getString("source");
                                String sortby = jObject .getString("sortBy");



                                    JSONArray jsonArray = jObject.getJSONArray("articles");
                                    for (int i = 0; i < jsonArray.length(); i++) {


                                        JSONObject jsonObject = jsonArray.getJSONObject(i);

                    String author = jsonObject.getString("author");
                    String title= jsonObject.getString("title");
                    String description= jsonObject.getString("description");
                    String url= jsonObject.getString("url");   
                    String urlToImage= jsonObject.getString("urlToImage");    
                    String publishedAt= jsonObject.getString("publishedAt");                                    




                                              }





                                } else {

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {

                            Log.e("error", "" + volleyError.getMessage());


                        }
                    }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {

                    Map<String, String> params = new HashMap<String, String>();
                  //put your parameter in the hash map variable params if you using post request


                    return params;
                }
            };

            RequestQueue notificationqueue = Volley.newRequestQueue(getContext());

            notificationqueue.add(notificationrequest);

并且不要忘记把凌空的依赖性放在一起。

答案 3 :(得分:0)

尝试这种方式来获得结果

JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, url, new

            Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray obj = response.getJSONArray("articles");

                        for (int i = 0; i < obj.length(); i++) {

                            JSONObject jsonObject = obj.getJSONObject(i);



                            String type = jsonObject.getString("author");

                            // check the other values like this so on..

                        }

                    }
                    catch (JSONException e) {

                        e.printStackTrace();
                    }
                }
            },null);

答案 4 :(得分:0)

    public void onResponse(Object response) {
            JSONArray jsonArray = null;
            try {
            Log.e("status",((JSONObject)response).getString("status"));
            Log.e("source",((JSONObject)response).getString("source"));
            Log.e("sortBy",((JSONObject)response).getString("sortBy"));
            Log.e("articles",((JSONObject)response).getString("articles"));//Notice than the articles string could not be completly display in the Log if it is too long

                //if you want to browse the table of articles
                jsonArray = ((JSONObject)response).getJSONArray("articles");
                for (int i = 0 ; i < jsonArray.length() ; i++){
                    Log.e("Item "+i,jsonArray.getJSONObject(i).getString("source"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
    }

答案 5 :(得分:0)

 @Override
 public void onResponse(JSONObject response) {

   try {

       JSONArray array=response.getJSONArray("articles");

          for (int i=0;i<array.length();i++){

               JSONObject object=array.getJSONObject(i);
               String title=object.get("title").toString();

          }

      } catch (JSONException e) {

        e.printStackTrace();

      }

   }