2011-11-11 30 views
39

Eventuali duplicati:
JSON Array iteration in Android/JavaCome analizzare la stringa json in Android?

sto recupero stringa JSON dal server e ho già ottenuto stringa JSON dal codice. Ma non ho capito come analizzarlo.

Qui di seguito è la mia stringa JSON

{ 
    "university": { 
     "name": "oxford", 
     "url": "http://www.youtube.com" 
    }, 
    "1": { 
     "id": "2", 
     "title": "Baseball", 
     "datetime": "2011-11-11 10:41:46" 
    }, 
    "2": { 
     "id": "1", 
     "title": "Two basketball team players earn all state honors", 
     "datetime": "2011-11-11 10:40:57" 
    } 
} 

Si prega di fornire alcuna guida o frammento di codice.

risposta

89

classi Uso JSON per l'analisi es

JSONObject mainObject = new JSONObject(Your_Sring_data); 
JSONObject uniObject = mainObject.getJSONObject("university"); 
String uniName = uniObject.getJsonString("name"); 
String uniURL = uniObject.getJsonString("url"); 

JSONObject oneObject = mainObject.getJSONObject("1"); 
String id = oneObject.getJsonString("id"); 
.... 
+0

è possibile ottenere quanti oggetti in stringa json – helloDroid

+2

Sì, è sufficiente utilizzare "mainObject.length();" – Arslan

+2

Modificato per usare 'getString()' invece di 'getJSONObject()' quando si ottengono valori stringa. L'uso di 'getJSONObject()' ha causato una JSONException quando ho eseguito un codice simile che è stato corretto usando 'getString()'. – Shef

9

seguito è il legame che guida in parsing stringa JSON in Android.

http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

Sempre secondo il codice stringa JSON frammento deve essere qualcosa di simile: -

JSONObject mainObject = new JSONObject(yourstring); 

JSONObject universityObject = mainObject.getJSONObject("university"); 
JSONString name = universityObject.getJsonString("name"); 
JSONString url = universityObject.getJsonString("url"); 

Lo stesso vale per un altro oggetto.

Problemi correlati