0

我想知道如何将来自服务器的 http 响应转换为适当的可解析 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 数组,我还不知道我必须如何使用输入流和所有这些实体,因此任何帮助将不胜感激。

4

5 回答 5

1

请看这个,很简单

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

将 IS 转换为字符串

 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 对象

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

从对象获取数组

 // Getting Array of Contacts
    JSONArray  contacts = json.getJSONArray("users");
于 2012-05-25T10:51:12.013 回答
1

您可以使用

  1. GSON
  2. 杰克逊

如果你想使用来自 json.org 的默认 json,那么 import org.json.JSONArray;你可以这样做:

JSONArray jsonArray = new JSONArray(yourJsonString);

见:http ://www.vogella.com/articles/AndroidJSON/article.html

于 2012-05-25T10:53:35.383 回答
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");
   }

我相信你可以根据你的需要调整它

于 2012-05-25T10:54:34.240 回答
1

如果您想将 Java 对象从 JSON 转换为 JSON,您可以查看:google-gson Java library

于 2012-05-25T11:01:09.997 回答
1

用两行代码

JSONObject jObj = new JSONObject(responsesrch.toString());
JSONArray jArr=jObj.getJSONArray("users");
于 2012-05-25T11:04:53.907 回答