2012-07-20 12 views
7

Estoy teniendo una aplicación en la que quiero obtener datos json de un servidor web php a Android. Lo que estoy teniendo es una url y presionar esa url me da los datos json como
{"items":[{"latitude":"420","longitude":"421"}]}. Pero quiero recuperar este formato json en mi móvil Android y obtener los valores de latitud y longitud del formato json.cómo obtener datos json del servidor php en el móvil Android

¿cómo podemos conseguir eso en el móvil Android ...?

Gracias de antemano ..

+2

Uso HTTPClient en android para el intercambio de datos con el servidor. Si te quedas atascado, publica tu código e intentaremos ayudarlo. –

Respuesta

9

En primer lugar hacer la conexión URL

String parsedString = ""; 

    try { 

     URL url = new URL(yourURL); 
     URLConnection conn = url.openConnection(); 

     HttpURLConnection httpConn = (HttpURLConnection) conn; 
     httpConn.setAllowUserInteraction(false); 
     httpConn.setInstanceFollowRedirects(true); 
     httpConn.setRequestMethod("GET"); 
     httpConn.connect(); 

     InputStream is = httpConn.getInputStream(); 
     parsedString = convertinputStreamToString(is); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

JSON cadena

{ 
"result": "success", 
"countryCodeList": 
[ 
    {"countryCode":"00","countryName":"World Wide"}, 
    {"countryCode":"kr","countryName":"Korea"} 
] 
} 

A continuación me retracto detalles países

JSONObject json = new JSONObject(jsonstring); 
JSONArray nameArray = json.names(); 
JSONArray valArray = json.toJSONArray(nameArray); 

JSONArray valArray1 = valArray.getJSONArray(1); 

valArray1.toString().replace("[", ""); 
valArray1.toString().replace("]", ""); 

int len = valArray1.length(); 

for (int i = 0; i < valArray1.length(); i++) { 

Country country = new Country(); 
JSONObject arr = valArray1.getJSONObject(i); 
country.setCountryCode(arr.getString("countryCode"));       
country.setCountryName(arr.getString("countryName")); 
arrCountries.add(country); 
} 




public static String convertinputStreamToString(InputStream ists) 
     throws IOException { 
    if (ists != null) { 
     StringBuilder sb = new StringBuilder(); 
     String line; 

     try { 
      BufferedReader r1 = new BufferedReader(new InputStreamReader(
        ists, "UTF-8")); 
      while ((line = r1.readLine()) != null) { 
       sb.append(line).append("\n"); 
      } 
     } finally { 
      ists.close(); 
     } 
     return sb.toString(); 
    } else { 
     return ""; 
    } 
} 
+0

¿Qué es este método 'convertinputStreamToString (is)'? –

+0

He agregado ese método – Nirali

0

usar algo como :

try { 
    HttpParams params = new BasicHttpParams(); 
    HttpConnectionParams.setSoTimeout(params, 0); 
    HttpClient httpClient = new DefaultHttpClient(params); 

    //prepare the HTTP GET call 
    HttpGet httpget = new HttpGet(urlString); 
    //get the response entity 
    HttpEntity entity = httpClient.execute(httpget).getEntity(); 

    if (entity != null) { 
     //get the response content as a string 
     String response = EntityUtils.toString(entity); 
     //consume the entity 
     entity.consumeContent(); 

     // When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources 
     httpClient.getConnectionManager().shutdown(); 

     //return the JSON response 
     JSONObject object = new JSONObject(response.trim()); 
     JSONArray jsonArray = object.getJSONArray("items"); 
     if(jsonArray != null) { 
      for(int i = 0 ; i < jsonArray.length() ; i++) { 
       JSONObject object1 = (JSONObject) jsonArray.get(i); 
       String latitude = object1.getString("latitude"); 
       String longitude = object1.getString("longitude"); 
      } 
     } 
    } 
}catch (Exception e) { 
    e.printStackTrace(); 
} 
+0

su código va en el bloque catch ... ¿por qué es así? –

+0

si me dices cuál es la excepción, puedo ayudarte, este código me funciona, excepto que la parte JSON es diferente. – Nermeen

+0

No sé cuál es la excepción, pero cuando brindo algo en el bloque catch se tuesta, pero cuando brindo por la latitud y la longitud, no brindis. –

1
String jsonStr = '{"menu": {' + 
     '"id": "file",' + 
     '"value": "File",' + 
     '"popup": {' + 
      '"menuitem": [' + 
      '{"value": "New", "onclick": "CreateNewDoc()"},' + 
      '{"value": "Open", "onclick": "OpenDoc()"},' + 
      '{"value": "Close", "onclick": "CloseDoc()"}' + 
      ']' + 
     '}' + 
     '}}'; 

Esa cadena JSON es en realidad de http://json.org/example.html. Fue el mejor que pude encontrar para este ejemplo dado.

Ahora que tenemos eso en su lugar, comencemos a usar JSONObject. Necesitará la siguiente importación para que esto funcione: import org.json.JSONObject;

JSONObject jsonObj = new JSONObject(jsonStr); 

Con eso instanciado, podemos hacer lo siguiente para retreive diferentes piezas de datos de la cadena JSON -

// grabbing the menu object 
JSONObject menu = jsonObj.getJSONObject("menu"); 


Reading =========> HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 
      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(); 
       result=sb.toString();=======>Here result is the json string 


// these 2 are strings 
String id = menu.getString("id"); 
String value = menu.getString("value"); 

// the popop is another JSON object 
JSONObject popup = menu.getJSONObject("popup"); 

// using JSONArray to grab the menuitems from under popop 
    JSONArray menuitemArr = popupObject.getJSONArray("menuitem"); 

// lets loop through the JSONArray and get all the items 
for (int i = 0; i < menuitemArr.length(); i++) { 
// printing the values to the logcat 
Log.v(menuitemArr.getJSONObject(i).getString("value").toString()); 
Log.v(menuitemArr.getJSONObject(i).getString("onclick").toString()); 
} 

Para un ejemplo sencillo clic here

+0

¿cómo conseguiré esta cadena json en mi programa? –

+0

que puede convertir su cadena de retorno en php en formato json –

+0

mi URL de php está devolviendo el formato json, pero la cuestión es cómo voy a obtener eso en mi progarm? –

1

enviar una solicitud desde el cliente de Android

public static JSONObject getJSONFromHttpPost(String URL) { 

    try{ 
    // Create a new HttpClient and Post Header 
    DefaultHttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost(URL); 
    String resultString = null; 




     long t = System.currentTimeMillis(); 
     HttpResponse response = (HttpResponse) httpclient.execute(httpPost); 
     System.out.println("HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]"); 
     // Get hold of the response entity (-> the data): 
     HttpEntity entity = response.getEntity(); 

     if (entity != null) { 
      // Read the content stream 
      InputStream instream = entity.getContent(); 

      // convert content stream to a String 
      resultString= convertStreamToString(instream); 
      instream.close(); 
      System.out.println("result String : " + resultString); 
      //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]" 
      System.out.println("result String : " + resultString); 
      // Transform the String into a JSONObject 
      JSONObject jsonObjRecv = new JSONObject(resultString); 
      // Raw DEBUG output of our received JSON object: 
      System.out.println("<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>"); 


      return jsonObjRecv; 
     } 
     }catch(Exception e){e.printStackTrace();} 


     return null; 

}

aquí es la función para convertir la cadena

private static String convertStreamToString(InputStream is) { 

    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 

    String line =""; 
    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(); 
} 

ahora todo lo que tiene que hacer es echo su cadena en formato JSON en el servidor

Cuestiones relacionadas