【发布时间】:2016-06-28 05:35:18
【问题描述】:
它实际上是一个简单的代码,因为缺乏基本的我仍然无法处理这个。
在我自己的 Api 上创建一个 Post JSON 方法后,我得到以下响应
[{"id":"2"}]
我想要实现的是我想获得这个“id”的值,即“2”。
我在我的私有 void 方法中尝试了以下代码
private void getUserID() {
StringRequest stringRequest = new StringRequest(Method.POST,Constants.GET_USER_ID,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("id").toString());
String idUser = jsonObject.optString("id").toString();
}
output.setText(idUser);
} catch (JSONException e) {e.printStackTrace();}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put(Constants.KEY_A, username);
map.put(Constants.KEY_B, password);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
我从here 得到它。
有点浪费,因为我的数组中只有一个列表对象,而且我认为 for 循环在这里并不重要。
【问题讨论】:
-
strJson是 JSONArray 而不是 JSONObject 所以这样做:JSONArray jsonArray = new JSONArray(strJson); int _id=jsonArray.getJSONObject(0).getInt("id");如果 JSONArray 只包含单个项目,则不需要使用 for-loop -
如果你只有一个项目然后删除 jsonarray.. 并做出这样的响应 {"id":"2"}..then get id