2012-06-20 21 views
22
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://my.server:8080/android/service.php"); 


List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
nameValuePairs.add(new BasicNameValuePair("action", "getjson")); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

HttpResponse response = httpclient.execute(httppost); 

service.php genera una cadena json. ¿Cómo puedo obtenerlo de mi response? Por cierto; He incluido la biblioteca GSON, ¿puedo usar algún método aquí?obtener json de HttpResponse

Soluciones similares a éste se ve muy feo, IMO: best way to handle json from httpresponse android

Hay mucho haber mejores maneras, ¿verdad?

Cualquier ayuda se agradece, gracias


Actualización:

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

parece hacer el truco. Solo hay un pequeño problema: la cadena está envuelta con los corchetes []. ¿Debo eliminarlos manualmente? Ellos son generadas por PHP: s json_encode()

+1

Los corchetes denotan una matriz JSON. Debe procesar la respuesta como tal. – Perception

+0

@Perception Correcto. Eliminé mi matriz de contenedores del código php, y se resolvió el problema. Gracias – Johan

+0

@Johan ¿Podría publicar su respuesta y aceptarla para que otros la encuentren útil y sepan qué es exactamente lo que resolvió el problema? ¡Gracias! –

Respuesta

1

El problema estaba en mi archivo php. Al eliminar la matriz de contenedores del objeto codificado json, mi código Java funcionó.

0

Si estoy devolviendo una cadena JSON de mi servicio web, por lo general quieren obtener de nuevo a un objeto JSON de este modo:

String response = client.getResponse(); 

    if (responseCode == 200) 
    {     
     JSONObject obj = new JSONObject(response);                
    } 
+0

Se ve más limpio, gracias por la entrada. Sin embargo, el problema estaba relacionado con php, vea mi comentario anterior. – Johan

1

Con esta clase, puede obtener los datos JSON de un servidor o de su carpeta de activos. Se puede cambiar fácilmente a solo uno o el otro. Si necesita un adaptador, use el jgilfelt created here on getHub.

@Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 

     Bundle getArgs = this.getArguments(); 
     String URI = getArgs.getString(KEY_URI);//OR YOU CAN HARD CODE THIS OR GET THE STRING ANYWAY YOU LIKE. 

     new GetJSONTask().execute(URI); 
    } 

    class GetJSONTask extends AsyncTask<String, Integer, String> { 

     protected String doInBackground(String... arg0) { 

      String uri = arg0[0]; 

      InputStream is = null; 

      if (uri.contains("http") == true) {// Get JSON from URL 
       try { 
        DefaultHttpClient httpClient = new DefaultHttpClient(); 
        HttpPost httpPost = new HttpPost(uri); 
        HttpResponse httpResponse = httpClient.execute(httpPost); 
        HttpEntity httpEntity = httpResponse.getEntity(); 
        is = httpEntity.getContent(); 

        BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8")); 
        while ((line = rd.readLine()) != null) { 
         json += line; 
        } 
        rd.close(); 
        return json; 
       } catch (Exception e) { 
        e.printStackTrace(); 
        return null; 
       } 
      } else {// Get JSON from Assets 

       Writer writer = new StringWriter(); 
       char[] buffer = new char[1024]; 

       try { 
        InputStream jsonFile = getActivity().getAssets().open(uri); 
        Reader reader = new BufferedReader(new InputStreamReader(jsonFile, "UTF-8")); 
        int n; 
        while ((n = reader.read(buffer)) != -1) { 
         writer.write(buffer, 0, n); 
        } 
        jsonFile.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
       json = writer.toString(); 
       // return JSON String 
       return json; 
      } 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      try { 
       showData(result); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
       Toast.makeText(getActivity(), "something went wrong", Toast.LENGTH_SHORT).show(); 
      } 
     } 
    } 

    private void showData(String json) throws JSONException { 
     JSONObject o = new JSONObject(json); 
     JSONArray data = o.getJSONArray("results"); 
    } 
} 
18

Creo que el problema con el que te estás encontrando es uno similar al que acabo de toparme. Si ejecuta:

 
String json_string = EntityUtils.toString(response.getEntity()); 
JSONObject temp1 = new JSONObject(json_string); 

El código anterior lanzar una excepción y parece que los soportes de matriz JSON son los culpables. ¡Pero está bien tener una matriz JSON como elemento de nivel superior! Sólo tiene que utilizar JSONArray() en lugar de JSONObject:

 
String json_string = EntityUtils.toString(response.getEntity()); 
JSONArray temp1 = new JSONArray(json_string); 

lo que tiene que saber si usted está recibiendo un JSONArray o un único diccionario que es un JSONObject en el código JSON.

Si está acostumbrado a las bibliotecas de análisis iOS/Objective-C JSON, utiliza el mismo elemento de nivel superior para tratar con diccionarios json y json array, por lo que cambiar al mundo JAVA/Android me confundió con dos tipos de manejo JSON según el nivel superior devuelto.

Cuestiones relacionadas