Obtener un objeto JSON de una respuesta HTTP


80

Quiero obtener un JSONobjeto de una respuesta Http get:

Aquí está mi código actual para Http get:

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 solo obtengo un objeto de cadena. ¿Cómo puedo recuperar un objeto JSON?


1
¿Qué obtienes en tu cadena de resultados?
— R4chi7

y ¿por qué estás usando response.getEntity () dos veces?
— R4chi7

Para recuperar un objeto JSON, ¿no debe conectarse el servidor web para enviar un JSON? ¿Hace eso?
— rockstar

@Zapnologica revisa mi respuesta. También vea la respuesta de agen451
— rockstar

Respuestas:


67

La cadena que obtiene es solo 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);

¿Qué pasa si en el caso de HttpExchange ..?
— Hema

@Renan Bandeira Estoy probando su código para convertir mi respuesta http a un objeto json y recibo este error Error:(47, 50) java: incompatible types: java.lang.StringBuffer cannot be converted to java.util.Map
— Christos Karapapas

@Karapapas ¿puedes mostrar tu código? Mi respuesta fue en 2013. Le recomendaría que use algo como Retrofit y Gson / Jackson para hacer frente a las solicitudes y la serialización de Json.
— Renan Bandeira

¿cómo puedo hacer esta misma tarea en c #?
— Farrukh Sarmad

10

Haz esto para obtener el JSON

String json = EntityUtils.toString(response.getEntity());

Más detalles aquí: obtenga json de HttpResponse


33
¡Eso es una cadena, no un JSON!
— Francisco Corrales Morales

6
¿Por qué esto tiene tantos votos a favor? Esto es solo una toString()función, básicamente lo mismo que está haciendo el OP.
— cst1992

Al menos esto elimina una gran cantidad de código de sobrecarga de bajo nivel del OP. Vea la publicación de @Catalin Pirvu a continuación para obtener una solución más completa.
— Cesar

9

Esta no es la respuesta exacta a su pregunta, pero esto puede ayudarlo

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");

8

Sin una mirada a su salida JSON exacta, es difícil darle un código de trabajo. Este tutorial es muy útil, pero podría usar algo como:

JSONObject jsonObj = new JSONObject("yourJsonString");

Luego puede recuperar de este objeto json usando:

String value = jsonObj.getString("yourKey");

1
Muy buen tutorial. "En general, todos los nodos JSON comenzarán con un corchete o con un corchete. La diferencia entre [y {es, el corchete ([) representa el inicio de un nodo JSONArray mientras que el corchete ({) representa JSONObject. Así que mientras para acceder a estos nodos, debemos llamar al método apropiado para acceder a los datos. Si su nodo JSON comienza con [, entonces deberíamos usar el método getJSONArray (). Igual que si el nodo comienza con {, entonces deberíamos usar el método getJSONObject () ".
— otro

3

Necesita usar JSONObjectcomo 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..


Hola Apnologica .. en caso de que alguna de las respuestas satisfaga su necesidad, por favor acéptelo para beneficiar a otros en llegar a la respuesta correcta fácilmente. gracias
— Sushil

2

En aras de una solución completa a este problema (sí, sé que esta publicación murió hace mucho tiempo ...):

Si quieres un JSONObject, primero obtén un Stringdel result:

String jsonString = EntityUtils.toString(response.getEntity());

Entonces puedes obtener tu JSONObject:

JSONObject jsonObject = new JSONObject(jsonString);

Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.