我想知道如何在适当的可解析JSON数组中转换来自服务器的http响应
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数组,我不知道如何使用输入流和所有这些实体,因此非常感谢任何帮助
答案 0 :(得分:1)
请看这个,很简单
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
将IS转换为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());
}
将String转换为Json对象
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
从Object获取数组
// Getting Array of Contacts
JSONArray contacts = json.getJSONArray("users");
答案 1 :(得分:1)
您可以使用
如果你想使用json.org中的默认json,那么导入org.json.JSONArray;
你可以这样做:
JSONArray jsonArray = new JSONArray(yourJsonString);
请参阅:http://www.vogella.com/articles/AndroidJSON/article.html
答案 2 :(得分: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");
}
我相信你可以根据自己的需要调整它
答案 3 :(得分:1)
如果要将Java对象从/转换为JSON,可以查看:google-gson Java library
答案 4 :(得分:1)
使用两行代码
JSONObject jObj = new JSONObject(responsesrch.toString());
JSONArray jArr=jObj.getJSONArray("users");