2012-03-07 24 views
51

¿Dónde puedo encontrar instrucciones paso a paso sobre cómo analizar una fuente JSON en Android? Solo soy un principiante de Android que quiere aprender.Cómo analizar JSON en Android

+2

hay un analizador JSON incrustado en el SDK. ver http://developer.android.com/reference/org/json/package-summary.html – njzk2

+0

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

+0

Eche un vistazo a todos los enlaces ** Relacionados ** en el lado derecho - hay un _ton_ de preguntas similares. Apreciamos un poco de esfuerzo antes de hacer preguntas. –

Respuesta

3

He codificado un ejemplo simple para usted y anotado la fuente. El ejemplo muestra cómo agarrar JSON en vivo y analizar en un JSONObject para la extracción de detalle:

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

vez que tenga su JSONObject se refieren a la SDK para obtener información sobre cómo extraer los datos que necesita.

+0

Hola, lo he puesto, pero he recibido errores. He importado todo, pero sigo teniendo problemas. – iamlukeyb

+0

Tendrá que ajustar el bloque de código anterior en un try-catch. He editado el código para reflejar esto. – Ljdawson

+0

¿Todavía tiene problemas? – Ljdawson

111

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

Consigue tu 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 usted tiene su JSON, ¿y qué?

Crear un JSONObject:

JSONObject jObject = new JSONObject(result); 

para obtener una cadena específica

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

Para obtener una específica booleano

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

Para obtener un número entero específico

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

Para obtener una específica largo

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

Para obtener un específico doble

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

Para obtener un específico JSONArray:

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

También podría haber un caso cuando reciba un JSONArray y si intenta JSONObject jObject = new JSONObject (resultado) - obtendrá una excepción sobre el análisis. En tal caso, JSONArray jArray = new JSONArray (resultado) funcionaría. – Stan

9
  1. escritura JSON Analizador clase de datos

    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 JSON Una vez que ha creado la clase analizador próximo thi ng 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 usando 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(); 
} 
0

intente seguir este tutorial http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ Hope esto le ayudará a empezar con JSONParsing

+0

Probé la muestra de Android Hive (http://www.androidhive.info/2012/01/android-json-parsing-tutorial/) ....... Pero el autor del sitio tiene algunos errores tipográficos en es ... pero es un gran lugar para aprender programación de Android para principiantes ... ¡gracias por la fuente! – Devrath

Cuestiones relacionadas