¿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
Respuesta
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.
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
}
}
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
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; } }
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();
}
intente seguir este tutorial http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ Hope esto le ayudará a empezar con JSONParsing
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
- 1. Cómo analizar json string en Android?
- 2. Cómo analizar un objeto JSON en Android
- 3. Cómo analizar esta matriz JSON en Android
- 4. Cómo analizar JSON (AS3)
- 5. Javascript cómo analizar matrices JSON
- 6. Usar GSON en Android para analizar un objeto JSON complejo
- 7. ¿Cómo puedo analizar JSON en Perl?
- 8. Cómo analizar matriz JSON en jQuery?
- 9. ¿Cómo puedo analizar JSON en Pig?
- 10. Cómo analizar una cadena JSON en Delphi?
- 11. cómo analizar JSON en Objective C - SBJSON
- 12. objeto Analizar JSON en JavaScript
- 13. Analizar JSON con org.json
- 14. Json en Android
- 15. Analizar JSON en una salida amistosa ListView
- 16. cómo analizar JSON anidada con Aeson
- 17. Cómo analizar datos JSON con jQuery/JavaScript?
- 18. Cómo analizar un objeto json usando jquery
- 19. Obtener y analizar JSON en Actionscript
- 20. Usar NSJSONSerialization para analizar JSON
- 21. Cómo analizar una cadena JSON en JsonNode en Jackson?
- 22. ¿Cómo analizar los SMS entrantes en Android?
- 23. Cómo analizar json de una solicitud POST entrante en Rails?
- 24. cómo analizar la respuesta JSON en Blackberry/J2ME?
- 25. ¿cómo puedo analizar una cadena json en nsdictionary?
- 26. Obtener ColdFusion para analizar una solicitud JSON
- 27. NoClassDefFoundError JsonAutoDetect al analizar el objeto JSON
- 28. Android Internal Storage, cómo analizar correctamente un archivo de texto JSON
- 29. Cómo analizar el objeto JSON en el iPhone SDK (XCode) usando JSON-Marco
- 30. ¿Cómo uso Google Json Parsing API (Gson) para analizar algunos campos dinámicos en my json?
hay un analizador JSON incrustado en el SDK. ver http://developer.android.com/reference/org/json/package-summary.html – njzk2
http://stackoverflow.com/a/2840873/643350 – Dipin
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. –