【问题标题】:Parse JSON objects within JSON array with android volley library使用 android volley 库解析 JSON 数组中的 JSON 对象
【发布时间】:2016-10-23 00:33:26
【问题描述】:

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

{ “状态”:“好的”, “来源”:“技术紧缩”, “排序依据”:“顶部”, “文章”:[ { “作者”:“英格丽德·伦登,菲茨·泰珀”, "title": "确认:AT&T 以 $85.4B 现金和股票收购时代华纳", “描述”:“经过几天的猜测,交易现在正式确定:AT&T 以 850 亿美元现金和股票的形式收购时代华纳,为……”, “网址”:“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", “发布时间”:“2016-10-23T00:02:34Z” },

我想访问第一个对象,然后是下一个,然后是下一个。欣赏。

【问题讨论】:

标签: android json android-volley


【解决方案1】:

这应该显示标题列表

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());
        }
   });

【讨论】:

  • 不工作@Short 答案。在 log cat 中运行和响应代码 405 后返回空白屏幕
  • 将答案从 Request.Method.POST 更新为 Request.Method.GET
【解决方案2】:

首先你必须使用添加 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
    }

【讨论】:

    【解决方案3】:

    首先你检查这个 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);
    

    别忘了放置 volley 的 gradle 依赖。

    【讨论】:

      【解决方案4】:

      试试这个方法来得到你的结果

      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);
      

      【讨论】:

        【解决方案5】:
            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();
                    }
            }
        

        【讨论】:

          猜你喜欢
          • 2019-08-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多