我正在将url传递给服务器,并提供类似这样的数据,
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("firstname",firstname));
nameValuePairs.add(new BasicNameValuePair("lastname", lastname));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
它给出了像这样的回复
{
"message": "Successful",
"data": {
"user_id": 32,
"firstname": "myname",
"lastname": "lastname"
}
}
如何从上面的响应中获取user_id,或者还有其他任何方式。 请告诉我如何解决这个问题。谢谢你提前
答案 0 :(得分:0)
像这样:
try {
JSONObject obj = new JSONObject(response.getBody());
JSONObject objData = obj.getJSONObject("data");
Integer userId = objData.getInt("user_id");
} catch (JSONException jsEx) {
jsEx.printStackTrace();
}
答案 1 :(得分:0)
这样做,
首先使用此方法获取响应数据,
public String getResponseBody(final InputStream instream) throws IOException, ParseException {
if (instream == null) {
return "";
}
StringBuilder buffer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "utf-8"));
String line = null;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} finally {
instream.close();
reader.close();
}
return buffer.toString();
}
然后,
JSONObject results = new JSONObject(getResponseBody(httpEntity.getContent()));
JSONObject user = results.getJSONObject("data");
String userid = user.getString("user_id")
答案 2 :(得分:0)
在您的代码
之后添加此内容HttpEntity httpEntity = response.getEntity();
String responseJson = EntityUtils.toString(httpEntity);
在这里,你将把你的json作为字符串作为回应。 你必须解析这个json以得到这样的期望值。
try {
JSONObject obj = new JSONObject(responseJson);
JSONObject objData = obj.getJSONObject("data");
Integer userId = objData.getInt("user_id");
} catch (JSONException jsEx) {
jsEx.printStackTrace();
}
跳这会让你明白:)