Obtener un objeto JSON desde una respuesta HTTP
Quiero obtener un objeto JSON
de una respuesta Http obtener:
Aquí está mi código actual para el Http obtener:
- Iterate Json datos del servicio web en el orden correcto
- ¿Cuál es la mejor manera de tratar con el objeto JSON?
- Obtener JSONArray sin nombre de matriz?
- Android y GSON lanzando No-Args Constructor no encontrado excepción
- Tener problemas para vincular un objeto ksoap a un ArrayList en Android
protected String doInBackground(String... params) { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(params[0]); HttpResponse response; String result = null; try { response = client.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { // A Simple JSON Response Read InputStream instream = entity.getContent(); result = convertStreamToString(instream); // now you have the string representation of the HTML request System.out.println("RESPONSE: " + result); instream.close(); if (response.getStatusLine().getStatusCode() == 200) { netState.setLogginDone(true); } } // Headers org.apache.http.Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { System.out.println(headers[i]); } } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return result; }
Aquí está la función convertSteamToString:
private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); }
En este momento sólo estoy recibiendo un objeto de cadena. ¿Cómo puedo recuperar un objeto JSON?
- Actualizar City Spinner con notifyDataSetChanged después de seleccionar estado
- ¿Cómo obtener la ubicación actual de este código de mapa? También intento recibir datos del vehículo del servidor cuando estoy abierto el mapa
- Android Volley varias solicitudes
- Android JSON HttpClient para enviar datos al servidor PHP con HttpResponse
- Aparece la tecla "nameValuePairs" extraña cuando se utiliza Gson
- Cambio de Gson a Jackson para el análisis de JSON
- Actualización de datos de Json analizados en Listview
- Convertir el número decimal json a corto con valor hexadecimal
La cadena que obtiene es sólo JSON Object.toString (). Significa que obtiene el objeto JSON, pero en formato String.
Si se supone que debe obtener un objeto JSON puede simplemente poner:
JSONObject myObject = new JSONObject(result);
Haga esto para obtener el JSON
String json = EntityUtils.toString(response.getEntity());
Más detalles aquí: obtener json de HttpResponse
Sin una mirada en su salida exacta de JSON, es duro darle un cierto código de trabajo. Este tutorial es muy útil, pero puedes usar algo como:
JSONObject jsonObj = new JSONObject("yourJsonString");
A continuación, puede recuperar de este objeto json utilizando:
String value = jsonObj.getString("yourKey");
Esta no es la respuesta exacta para su pregunta, pero esto puede ayudarle
public class JsonParser { private static DefaultHttpClient httpClient = ConnectionManager.getClient(); public static List<Club> getNearestClubs(double lat, double lon) { // YOUR URL GOES HERE String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon); List<Club> ret = new ArrayList<Club>(); HttpResponse response = null; HttpGet getMethod = new HttpGet(getUrl); try { response = httpClient.execute(getMethod); // CONVERT RESPONSE TO STRING String result = EntityUtils.toString(response.getEntity()); // CONVERT RESPONSE STRING TO JSON ARRAY JSONArray ja = new JSONArray(result); // ITERATE THROUGH AND RETRIEVE CLUB FIELDS int n = ja.length(); for (int i = 0; i < n; i++) { // GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY JSONObject jo = ja.getJSONObject(i); // RETRIEVE EACH JSON OBJECT'S FIELDS long id = jo.getLong("id"); String name = jo.getString("name"); String address = jo.getString("address"); String country = jo.getString("country"); String zip = jo.getString("zip"); double clat = jo.getDouble("lat"); double clon = jo.getDouble("lon"); String url = jo.getString("url"); String number = jo.getString("number"); // CONVERT DATA FIELDS TO CLUB OBJECT Club c = new Club(id, name, address, country, zip, clat, clon, url, number); ret.add(c); } } catch (Exception e) { e.printStackTrace(); } // RETURN LIST OF CLUBS return ret; } } Again, it's relatively straight forward, but the methods I'll make special note of are: JSONArray ja = new JSONArray(result); JSONObject jo = ja.getJSONObject(i); long id = jo.getLong("id"); String name = jo.getString("name"); double clat = jo.getDouble("lat");
Necesita utilizar JSONObject
como a continuación:
String mJsonString = downloadFileFromInternet(urls[0]); JSONObject jObject = null; try { jObject = new JSONObject(mJsonString); } catch (JSONException e) { e.printStackTrace(); return false; }
…
private String downloadFileFromInternet(String url) { if(url == null /*|| url.isEmpty() == true*/) new IllegalArgumentException("url is empty/null"); StringBuilder sb = new StringBuilder(); InputStream inStream = null; try { url = urlEncode(url); URL link = new URL(url); inStream = link.openStream(); int i; int total = 0; byte[] buffer = new byte[8 * 1024]; while((i=inStream.read(buffer)) != -1) { if(total >= (1024 * 1024)) { return ""; } total += i; sb.append(new String(buffer,0,i)); } } catch(Exception e ) { e.printStackTrace(); return null; }catch(OutOfMemoryError e) { e.printStackTrace(); return null; } return sb.toString(); } private String urlEncode(String url) { if(url == null /*|| url.isEmpty() == true*/) return null; url = url.replace("[",""); url = url.replace("]",""); url = url.replaceAll(" ","%20"); return url; }
Espero que esto te ayude
Hay un constructor JSONObject para convertir una String en un objeto JSONObject:
http://developer.android.com/reference/org/json/JSONObject.html#JSONObject(java.lang.String)
- Activar y desactivar un receptor de difusión
- Offseting el centro del MapFragment para una animación moviendo tanto el lat / lng de destino como el nivel de zoom