studio recorrer jsonarray guardar example datos crear consumir array android json parsing

recorrer - ¿Cómo analizo JSON en Android?



json array android studio (3)

Nota: esta respuesta no se ha actualizado desde 2013. La forma sugerida para descargar el json ya no se recomienda para Android ya que el cliente http se ha eliminado del SDK a partir de la API 23.
Sin embargo, la lógica de análisis a continuación todavía se aplica

Android tiene todas las herramientas que necesita para analizar json incorporado. Sigue el ejemplo, no hay necesidad de GSON ni nada de eso.

Obtenga su 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){} }

ahora tienes tu JSON, ¿y qué?

Crea un JSONObject :

JSONObject jObject = new JSONObject(result);

Para obtener una cadena específica

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

Para obtener un booleano específico

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

Para obtener un entero específico

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

Para obtener un largo específico

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

Para obtener un doble específico

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

Para obtener un JSONArray específico:

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

Para obtener los elementos de la matriz

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 } }

Esta pregunta ya tiene una respuesta aquí:

¿Cómo puedo analizar un feed JSON en Android?


  1. Escribir clase JSON Parser

    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. Análisis de datos JSON Una vez que haya creado la clase de analizador, lo siguiente es saber cómo usar esa clase. A continuación estoy explicando cómo analizar el json (tomado en este ejemplo) usando la clase de analizador.

2.1. Almacene todos estos nombres de nodo en variables: en los contactos json tenemos elementos como nombre, correo electrónico, dirección, sexo y números de teléfono. Entonces, lo primero es almacenar todos estos nombres de nodo en variables. Abra su clase de actividad principal y declare almacenar todos los nombres de nodo en variables estáticas.

// 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. Usa la clase de analizador para obtener JSONObject y recorrer cada elemento json. A continuación, estoy creando una instancia de la clase JSONParser y utilizando for loop, estoy recorriendo cada elemento json y finalmente almacenando cada json data en la variable.

// 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(); }


He codificado un simple ejemplo para ti y anotado la fuente. El ejemplo muestra cómo capturar json en vivo y analizar en un JSONObject para la extracción de detalles:

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 vez que tenga su JSONObject, consulte el SDK para obtener detalles sobre cómo extraer los datos que necesita.