Search code examples
androidjsonandroidhttpclient

Receiving a JSON bigger than a String in Android


I'm new with Android and I have a problem that I can't resolve with server communications and JSONs:

I'm receiving a JSON object from a server using the HttpClient class, like a lot of examples that I've seen:

//Crear un cliente por defecto 
HttpClient mCliente = new DefaultHttpClient();

//Indicar la url
StringBuilder sb = new StringBuilder([SERVER]);

//Establecer la conexión después de indicar la url
HttpPost mPost = new HttpPost(sb.toString());

//Creamos una lista de atributos
List<BasicNameValuePair> paresNombreValor = new ArrayList<BasicNameValuePair>();

//Añadimos los elementos a la lista
paresNombreValor.add(new BasicNameValuePair("operacion", "1"));  //Operación Login
paresNombreValor.add(new BasicNameValuePair("email", stringCorreo));
paresNombreValor.add(new BasicNameValuePair("password", stringPass));

//UrlEncodedFormEntity : Codificamos la lista para el envio por post
mPost.setEntity(new UrlEncodedFormEntity(paresNombreValor));

//Ejecutamos la solicitud y obtenemos una respuesta
HttpResponse respuesta = mCliente.execute(mPost);

//Obtenemos el contenido de la respuesta
HttpEntity entity = respuesta.getEntity();

//Convertimos el stream a un String 
BufferedReader buf = new BufferedReader(new InputStreamReader(entity.getContent()));

StringBuilder sb1 = new StringBuilder();
String line = null;

while ((line = buf.readLine()) != null) {
     sb1.append(line + "\r\n");
}
res = sb1.toString();
if (res != null)
{
JSONArray resultadoJSON= new JSONArray(res);   //<-- Here is my problem
...

The problem is that the JSON that I receive is bigger than a String and I haven't found other way to transform the reception into a JSON that not uses a String with the content as parameter.

Any Ideas?

Thank you very much


Solution

  • intend of converting your input stream to string Use JsonReader its allow you read json from Input Stream also will help to save memory