2013-06-16 28 views
12

voglio leggere queste righe JSON ma perché iniziare con JSONArray im un po 'confusocome analizzare JSONArray in Android

"abridged_cast": [ 
      { 
       "name": "Jeff Bridges", 
       "id": "162655890", 
       "characters": [ 
        "Jack Prescott" 
       ] 
      }, 
      { 
       "name": "Charles Grodin", 
       "id": "162662571", 
       "characters": [ 
        "Fred Wilson" 
       ] 
      }, 
      { 
       "name": "Jessica Lange", 
       "id": "162653068", 
       "characters": [ 
        "Dwan" 
       ] 
      }, 
      { 
       "name": "John Randolph", 
       "id": "162691889", 
       "characters": [ 
        "Capt. Ross" 
       ] 
      }, 
      { 
       "name": "Rene Auberjonois", 
       "id": "162718328", 
       "characters": [ 
        "Bagley" 
       ] 
      } 
     ], 

Ho solo bisogno di utilizzare il "nome" e salvare tutti come una stringa. (il valore della stringa sarà: Jeff Bridges, Charles Grodin, Jessica Lange, John Randolph, Rene Auberjonois).

questo è il mio codice:

try { 
     //JSON is the JSON code above 

     JSONObject jsonResponse = new JSONObject(JSON); 
     JSONArray movies = jsonResponse.getJSONArray("characters"); 
     String hey = movies.toString(); 


    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
+0

puoi pubblicare la stringa json completa? –

+0

Si sta recuperando l'array con il nome sbagliato. –

+0

Dovrebbe essere 'getJSONArray (" abridged_cast ")' e quindi for-loop – vorrtex

risposta

45

Se sei dopo il 'nome', perché il codice frammento di apparire come un tentativo di ottenere i 'caratteri'?

In ogni caso, questo non è diverso da qualsiasi altra operazione di tipo elenco o array: è sufficiente scorrere il set di dati e acquisire le informazioni a cui sei interessato. Il recupero di tutti i nomi dovrebbe essere simile al seguente:

List<String> allNames = new ArrayList<String>(); 

JSONArray cast = jsonResponse.getJSONArray("abridged_cast"); 
for (int i=0; i<cast.length(); i++) { 
    JSONObject actor = cast.getJSONObject(i); 
    String name = actor.getString("name"); 
    allNames.add(name); 
} 

(digitato direttamente nel browser, quindi non testato).

+0

grazie lavorato! – digitalmidges

+1

cosa dire del json di questo formato [{"id": "1", "utente": "alll"}, {"id": "1", "utente": "alll"}] – numerah

+5

@numerah: tu avere un array senza una chiave, quindi basta analizzare il json direttamente in un 'JSONArray'. –

4

getJSONArray (attrName) ti porterà una matrice dall'oggetto di quel dato nome dell'attributo nel tuo caso ciò che sta accadendo è che per

{"abridged_cast":["name": blah...]} 
^ its trying to search for a value "characters" 

ma è necessario entrare nella matrice e poi fare un la ricerca di "personaggi"

provare questo

String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}"; 

    JSONObject jsonResponse; 
    try { 
     ArrayList<String> temp = new ArrayList<String>(); 
     jsonResponse = new JSONObject(json); 
     JSONArray movies = jsonResponse.getJSONArray("abridged_cast"); 
     for(int i=0;i<movies.length();i++){ 
      JSONObject movie = movies.getJSONObject(i); 
      JSONArray characters = movie.getJSONArray("characters"); 
      for(int j=0;j<characters.length();j++){ 
       temp.add(characters.getString(j)); 
      } 
     } 
     Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show(); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

controllato :)

1

Ecco un modo migliore per farlo. Spero che questo aiuti

protected void onPostExecute(String result) { 
       Log.v(TAG + " result); 


       if (!result.equals("")) { 

        // Set up variables for API Call 
        ArrayList<String> list = new ArrayList<String>(); 

        try { 
         JSONArray jsonArray = new JSONArray(result); 

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

          list.add(jsonArray.get(i).toString()); 

         }//end for 
        } catch (JSONException e) { 
         Log.e(TAG, "onPostExecute > Try > JSONException => " + e); 
         e.printStackTrace(); 
        } 


        adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list); 
        listView.setAdapter(adapter); 
        listView.setOnItemClickListener(new OnItemClickListener() { 
         @Override 
         public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

          // ListView Clicked item index 
          int itemPosition = position; 

          // ListView Clicked item value 
          String itemValue = (String) listView.getItemAtPosition(position); 

          // Show Alert 
          Toast.makeText(ListViewData.this, "Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG).show(); 
         } 
        }); 

        adapter.notifyDataSetChanged(); 
...