Comment parsingr un stream JSON sous Android?
Remarque: cette réponse n’a pas été mise à jour depuis 2013. La manière suggérée de télécharger json n’est plus recommandée pour Android étant donné que le client http a été supprimé du sdk à partir d’api 23.
Cependant, la logique d’parsing ci-dessous s’applique toujours
Android a tous les outils dont vous avez besoin pour parsingr json intégré. Exemple suit, pas besoin de GSON ou quelque chose comme ça.
Obtenez votre 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; Ssortingng 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); SsortingngBuilder sb = new SsortingngBuilder(); Ssortingng line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toSsortingng(); } catch (Exception e) { // Oops } finally { try{if(inputStream != null)inputStream.close();}catch(Exception squish){} }
maintenant vous avez votre JSON, et alors?
Créez un object JSONObject :
JSONObject jObject = new JSONObject(result);
Pour obtenir une chaîne spécifique
Ssortingng aJsonSsortingng = jObject.getSsortingng("STRINGNAME");
Pour obtenir un booléen spécifique
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
Pour obtenir un entier spécifique
int aJsonInteger = jObject.getInt("INTEGERNAME");
Pour obtenir un long spécifique
long aJsonLong = jObject.getLong("LONGNAME");
Pour obtenir un double spécifique
double aJsonDouble = jObject.getDouble("DOUBLENAME");
Pour obtenir un object JSONArray spécifique:
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
Pour récupérer les éléments du tableau
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 } }
Ecriture de la classe JSON Parser
public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static Ssortingng json = ""; // constructor public JSONParser() {} public JSONObject getJSONFromUrl(Ssortingng 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); SsortingngBuilder sb = new SsortingngBuilder(); Ssortingng line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toSsortingng(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toSsortingng()); } // try parse the ssortingng to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toSsortingng()); } // return JSON Ssortingng return jObj; } }
Analyser les données JSON Une fois que vous avez créé la classe d’parsingur, la prochaine chose à faire est de savoir comment utiliser cette classe. Ci-dessous, j’explique comment parsingr le json (pris dans cet exemple) en utilisant la classe du parseur.
2.1. Stockez tous ces noms de nœuds dans des variables: dans les contacts json, nous avons des éléments tels que le nom, l’adresse électronique, l’adresse, le sexe et les numéros de téléphone. La première chose à faire est de stocker tous ces noms de nœuds dans des variables. Ouvrez votre classe d’activité principale et déclarez tous les noms de nœuds dans des variables statiques.
// url to make request private static Ssortingng url = "http://api.9android.net/contacts"; // JSON Node names private static final Ssortingng TAG_CONTACTS = "contacts"; private static final Ssortingng TAG_ID = "id"; private static final Ssortingng TAG_NAME = "name"; private static final Ssortingng TAG_EMAIL = "email"; private static final Ssortingng TAG_ADDRESS = "address"; private static final Ssortingng TAG_GENDER = "gender"; private static final Ssortingng TAG_PHONE = "phone"; private static final Ssortingng TAG_PHONE_MOBILE = "mobile"; private static final Ssortingng TAG_PHONE_HOME = "home"; private static final Ssortingng TAG_PHONE_OFFICE = "office"; // contacts JSONArray JSONArray contacts = null;
2.2. Utilisez la classe de l’parsingur pour obtenir JSONObject et parcourir chaque élément json. Ci-dessous, je crée une instance de la classe JSONParser et utilise for loop pour parcourir chaque élément json et stocker finalement chaque donnée json dans variable.
// Creating JSON Parser instance JSONParser jParser = new JSONParser(); // getting JSON ssortingng 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(); }
J’ai codé un exemple simple pour vous et annoté la source. L’exemple montre comment récupérer json en direct et parsingr un object JSONObject pour une extraction détaillée:
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")); Ssortingng 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(); }
Une fois que vous avez votre JSONObject, consultez le SDK pour plus de détails sur l’extraction des données dont vous avez besoin.