2012-03-07 36 views
51

Dove posso trovare le istruzioni dettagliate su come analizzare un feed JSON in Android? Sono solo un principiante di Android che vuole imparare.Come analizzare JSON in Android

+2

c'è un parser JSON incorporato nel SDK. vedi http://developer.android.com/reference/org/json/package-summary.html – njzk2

+0

http://stackoverflow.com/a/2840873/643350 – Dipin

+0

Dai uno sguardo a tutti i link ** correlati ** su il lato destro - ci sono un sacco di domande simili. Apprezziamo un po 'di sforzo prima di fare domande. –

risposta

3

Ho codificato un semplice esempio per te e ho annotato la fonte. L'esempio mostra come per afferrare JSON dal vivo e analizzare in un JSONObject per l'estrazione dettaglio:

try{ 
    // Create a new HTTP Client 
    DefaultHttpClient defaultClient = new DefaultHttpClient(); 
    // Setup the get request 
    HttpGet httpGetRequest = new HttpGet("http://example.json"); 

    // Execute the request in the client 
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest); 
    // Grab the response 
    BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); 
    String json = reader.readLine(); 

    // Instantiate a JSON object from the request response 
    JSONObject jsonObject = new JSONObject(json); 

} catch(Exception e){ 
    // In your production code handle any errors and catch the individual exceptions 
    e.printStackTrace(); 
} 

Una volta ottenuto il JSONObject si riferiscono alla SDK per i dettagli su come estrarre i dati necessari.

+0

Salve, ho inserito questo, ma ho ricevuto errori ho importato tutto ma ho ancora problemi – iamlukeyb

+0

Avrete bisogno di avvolgere il blocco di codice sopra in un try-catch, ho modificato il codice per riflettere questo. – Ljdawson

+0

Hai ancora problemi? – Ljdawson

111

Android ha tutti gli strumenti necessari per analizzare json built-in. Segue un esempio, non c'è bisogno di GSON o qualcosa del genere.

Crea il tuo JSON:

DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); 
HttpPost httppost = new HttpPost(http://someJSONUrl/jsonWebService); 
// Depends on your web service 
httppost.setHeader("Content-type", "application/json"); 

InputStream inputStream = null; 
String result = null; 
try { 
    HttpResponse response = httpclient.execute(httppost);   
    HttpEntity entity = response.getEntity(); 

    inputStream = entity.getContent(); 
    // json is UTF-8 by default 
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); 
    StringBuilder sb = new StringBuilder(); 

    String line = null; 
    while ((line = reader.readLine()) != null) 
    { 
     sb.append(line + "\n"); 
    } 
    result = sb.toString(); 
} catch (Exception e) { 
    // Oops 
} 
finally { 
    try{if(inputStream != null)inputStream.close();}catch(Exception squish){} 
} 

ora avete il vostro JSON, e allora?

Creare un JSONObject:

JSONObject jObject = new JSONObject(result); 

Per ottenere una stringa specifica

String aJsonString = jObject.getString("STRINGNAME"); 

Per ottenere una specifica booleano

boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME"); 

Per ottenere un numero intero specifica

int aJsonInteger = jObject.getInt("INTEGERNAME"); 

Per ottenere una specifica lunga

long aJsonLong = jObject.getBoolean("LONGNAME"); 

Per ottenere una specifica doppia

double aJsonDouble = jObject.getDouble("DOUBLENAME"); 

Per ottenere una specifica JSONArray:

JSONArray jArray = jObject.getJSONArray("ARRAYNAME"); 

di ottenere gli elementi dalla matrice

for (int i=0; i < jArray.length(); i++) 
{ 
    try { 
     JSONObject oneObject = jArray.getJSONObject(i); 
     // Pulling items from the array 
     String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray"); 
     String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY"); 
    } catch (JSONException e) { 
     // Oops 
    } 
} 
+0

Ci potrebbe anche essere un caso quando si riceve un JSONArray e se si tenta di JSONObject jObject = new JSONObject (result) - si otterrà un'eccezione sull'analisi. In tal caso, JSONArray jArray = new JSONArray (result) funzionerebbe. – Stan

9
  1. scrittura JSON parser Classe

    public class JSONParser { 
    
        static InputStream is = null; 
        static JSONObject jObj = null; 
        static String json = ""; 
    
        // constructor 
        public JSONParser() {} 
    
        public JSONObject getJSONFromUrl(String url) { 
    
         // Making HTTP request 
         try { 
          // defaultHttpClient 
          DefaultHttpClient httpClient = new DefaultHttpClient(); 
          HttpPost httpPost = new HttpPost(url); 
    
          HttpResponse httpResponse = httpClient.execute(httpPost); 
          HttpEntity httpEntity = httpResponse.getEntity(); 
          is = httpEntity.getContent(); 
    
         } catch (UnsupportedEncodingException e) { 
          e.printStackTrace(); 
         } catch (ClientProtocolException e) { 
          e.printStackTrace(); 
         } catch (IOException e) { 
          e.printStackTrace(); 
         } 
    
         try { 
          BufferedReader reader = new BufferedReader(new InputStreamReader(
            is, "iso-8859-1"), 8); 
          StringBuilder sb = new StringBuilder(); 
          String line = null; 
          while ((line = reader.readLine()) != null) { 
           sb.append(line + "\n"); 
          } 
          is.close(); 
          json = sb.toString(); 
         } catch (Exception e) { 
          Log.e("Buffer Error", "Error converting result " + e.toString()); 
         } 
    
         // try parse the string to a JSON object 
         try { 
          jObj = new JSONObject(json); 
         } catch (JSONException e) { 
          Log.e("JSON Parser", "Error parsing data " + e.toString()); 
         } 
    
         // return JSON String 
         return jObj; 
    
        } 
    } 
    
  2. di analisi JSON dati Una volta creato classe parser dopo ng è sapere come usare quella classe. Qui di seguito sto spiegando come analizzare il json (preso in questo esempio) usando la classe parser.

2.1.Memorizza tutti questi nomi di nodi in variabili: Nel contatto json abbiamo elementi come nome, indirizzo email, sesso e numeri di telefono. Quindi, la prima cosa è memorizzare tutti questi nomi di nodi in variabili. Aprire la classe di attività principale e dichiarare memorizzare tutti i nomi di nodo in variabili statiche.

// url to make request 
private static String url = "http://api.9android.net/contacts"; 

// JSON Node names 
private static final String TAG_CONTACTS = "contacts"; 
private static final String TAG_ID = "id"; 
private static final String TAG_NAME = "name"; 
private static final String TAG_EMAIL = "email"; 
private static final String TAG_ADDRESS = "address"; 
private static final String TAG_GENDER = "gender"; 
private static final String TAG_PHONE = "phone"; 
private static final String TAG_PHONE_MOBILE = "mobile"; 
private static final String TAG_PHONE_HOME = "home"; 
private static final String TAG_PHONE_OFFICE = "office"; 

// contacts JSONArray 
JSONArray contacts = null; 

2.2. Utilizzare la classe parser per ottenere JSONObject e il looping di ogni elemento json. Qui di seguito sto creando un'istanza della classe JSONParser e utilizzando per il loop sto facendo il giro di ogni elemento json e infine memorizzando ogni dato json in variabile.

// Creating JSON Parser instance 
JSONParser jParser = new JSONParser(); 

// getting JSON string from URL 
JSONObject json = jParser.getJSONFromUrl(url); 

try { 
    // Getting Array of Contacts 
    contacts = json.getJSONArray(TAG_CONTACTS); 

    // looping through All Contacts 
    for(int i = 0; i < contacts.length(); i++){ 
     JSONObject c = contacts.getJSONObject(i); 

     // Storing each json item in variable 
     String id = c.getString(TAG_ID); 
     String name = c.getString(TAG_NAME); 
     String email = c.getString(TAG_EMAIL); 
     String address = c.getString(TAG_ADDRESS); 
     String gender = c.getString(TAG_GENDER); 

     // Phone number is agin JSON Object 
     JSONObject phone = c.getJSONObject(TAG_PHONE); 
     String mobile = phone.getString(TAG_PHONE_MOBILE); 
     String home = phone.getString(TAG_PHONE_HOME); 
     String office = phone.getString(TAG_PHONE_OFFICE); 

    } 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 
0

prova a seguire questo tutorial http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ Spero che questo vi aiuterà a iniziare con JSONParsing

+0

Ho provato il campione da Android Hive (http://www.androidhive.info/2012/01/android-json-parsing-tutorial/) ....... Ma l'autore del sito ha alcuni errori di battitura in ma ... è un ottimo posto per imparare la programmazione Android per i principianti ... grazie per la fonte! – Devrath