2012-05-29 34 views
20

Desidero recuperare JSON da un servizio Web e analizzarlo in seguito.
Sono sulla buona strada?Come convertire HttpEntity in JSON?

HttpClient httpclient = new DefaultHttpClient(); 
    HttpGet httpget = new HttpGet(url); 
    HttpResponse response; 
    try { 
     response = httpclient.execute(httpget); 
     HttpEntity entity = response.getEntity(); 

     if (entity != null) { 
      // parsing JSON 
     } 

    } catch (Exception e) { 
    } 

Purtroppo non so come convertire HttpEntity in un JSONObject.

Questo è il mio JSON (estratto):

{ 
    "names": [ 
     { 
      "name": "Zachary" 
     }, 
     { 
      "name": "Wyatt" 
     }, 
     { 
      "name": "William" 
     } 
    ] 
} 

risposta

49

È possibile convertire stringa JSON come:

try { 
     response = httpclient.execute(httpget); 
     HttpEntity entity = response.getEntity(); 

     if (entity != null) { 
      String retSrc = EntityUtils.toString(entity); 
      // parsing JSON 
      JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object 

      JSONArray tokenList = result.getJSONArray("names"); 
      JSONObject oj = tokenList.getJSONObject(0); 
      String token = oj.getString("name"); 
     } 
} 
catch (Exception e) { 
    } 
+0

Si dice 'Tipo non corrispondente: non può convertire da Object a STRING', quindi l'ho cambiato in' stringa di token = (String) result.get ("token"); '. Ma sfortunatamente non ricevo nulla quando provo 'Log.d (" token ", token);', anche se l'entità è '! = Null' e ho JSON valido. – user1170330

+0

ok allora puoi inviarmi il tuo json feed link bez è possibile che il tuo oggetto json contenga un altro JsonArray, allora devi prima usare JSONArray e poi estrarre il valore dall'array –

+0

Si prega di notare l'aggiornamento (codice JSON). – user1170330

0

Utilizzare l'entity.getContent() per ottenere l'InputStream e convertirlo in stringa.

0

Prova questa

public String getMyFeed(){ 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpGet httpget = new HttpGet(url); 
    HttpResponse response = httpclien.execute(httpget); 

    HttpEntity entity = response.getEntity(); 
    HttpInputStream content = entity.getContent(); 

    StatusLine sl = response.getStatusLine(); 
    int statCode = sl.getStatusCode() 

    if (statCode ==200){ 

    // process it 

} 

} 


String readFeed = getMyFeed(); 
JSONArray jArr = new JSONArray(readFeed); 

for(int i=0 ; i<jArr.length ; i++) 
JSONObject jObj = jArr.getJSONObject(i);