2012-05-25 47 views
0

我想知道如何從服務器的HTTP響應轉換成合適的可解析JSON陣列JSON轉換

 try { 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost postRequest = new HttpPost(
        "http://riffre.com/chatapp/search.php?format=json"); 
      postRequest.setEntity(new UrlEncodedFormEntity(nameValuePair)); 
      ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
      responsesrch = httpClient.execute(postRequest, responseHandler); 

      Log.v("search response", responsesrch); 

這是我的代碼,我的名字值對的形式發佈了幾個參數,以服務器 和responseserch我得到的值是

{"users":[{"user":{"city":"gurgaon","username":"zxc","userid":"6","gender":"Male","images":"0"}},{"user":{"city":"gurgaon","username":"tarun","userid":"5","gender":"Male","images":"0"}},{"user":{"city":"gurgaon","username":"vips","userid":"4","gender":"Male","images":"0"}},{"user":{"city":"gurgaon","username":"rah","userid":"3","gender":"Male","images":"0"}},{"user":{"city":"gurgaon","username":"aak","userid":"2","gender":"Male","images":"0"}}]} 

,這是字符串格式,所以我想知道我怎麼可以把這個字符串轉換成JSON數組,我還不知道我是如何必須使用輸入流和所有這些實體,因此任何幫助不勝感激。

回答

1

請看看這個,這是簡單

http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

換算是爲String

try { 
      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(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

字符串轉換爲JSON對象從Object

try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

GET數組

// Getting Array of Contacts 
    JSONArray contacts = json.getJSONArray("users"); 
+0

HTTP兩行://www.androidcompetenc ycenter.com/2009/10/json-parsing-in-android/ –

1

這是我工作的代碼示例:

jArray = new JSONArray(result); 
    JSONObject json_data = null; 
    double[] tempLong = null; 
    double[] tempLat = null; 
    for (int i = 0; i < jArray.length(); i++) { 
     json_data = jArray.getJSONObject(i); 
     tempLong = new double[jArray.length()]; 
     tempLat = new double[jArray.length()]; 
     tempLong[i] = json_data.getDouble("longtitude"); 
     tempLat[i] = json_data.getDouble("latitude"); 
    } 

我相信你能適應它爲您的需求

1

隨着代碼

JSONObject jObj = new JSONObject(responsesrch.toString()); 
JSONArray jArr=jObj.getJSONArray("users");