2016-10-23 6 views
0

Ich habe eine JSON-Antwort vom Server, unten angehängt. Ich möchte diese Antwort mit Volley in Android analysieren. Wie analysiere ich die Objekte im Array?Parse JSON Objekte innerhalb JSON-Array mit Android-Volley-Bibliothek

 
    { 
    "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" 
    }, 

Ich möchte auf das erste Objekt zugreifen, und das nächste und das nächste danach. Schätzen.

+0

wissen Sie zu bekommen, wie Volley verwenden json vom Server zu bekommen? –

+0

können Sie mir sagen @RitikKumarAgrahari –

+0

Ich habe die Lösung gepostet, sehen Sie sich –

Antwort

3

Diese

eine Liste der Titel angezeigt werden soll
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()); 
     } 
    }); 
+0

Nicht funktioniert @Kurzantwort. Gibt einen leeren Bildschirm nach Ausführung und Antwortcode 405 im Protokoll cat zurück –

+0

Aktualisierte Antwort von * Request.Method.POST * auf * Request.Method.GET * –

0

Zuerst müssen Sie

Kompilierung 'com.mcxiaoke.volley: library-aar: 1.0.0' mit Volley-Bibliothek hinzufügen

in build.grdle Datei wie unten

gezeigt
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') 
} 

Dann müssen u eine uRL json Objekt 01 zu erhaltendanach u kann unter Code folgen 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(); 
    } 
} 

wie in Ihrem json u analysieren wollen "Artikel" Array zu analysieren, so u

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 
    } 
0

Erste Code unten verwenden, können Sie diese API überprüfen POST API oder GET API. Wenn diese API POST-Methode ist, übergeben Sie den Parameter in der Hashmap.Wenn es die GET API ist, dann übergeben Sie den Parameter mit der URL. und unter code wird dein gegebenes json analysiert.

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

und vergessen Sie nicht, die Großbuchstaben Abhängigkeit von Volley setzen.

0

auf diese Weise versuchen Sie Ihr Ergebnis

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