【发布时间】:2019-03-25 12:07:40
【问题描述】:
我需要从 JSON url 中检索一些值。下面的代码我试过了,但它没有给出任何错误或异常,但没有检索到值。
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://api.ipstack.com/111.125.204.140?
access_key=############";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONObject json = null;
try {
json = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
Log.d("errror",e.toString());// Not getting any error
}
String cityName = json.optString("type");// here iam not getting any value.
txtJson.setText(cityName);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
txtJson.setText("That didn't work!");
}
});
queue.add(stringRequest);
JSON 结构
{
"ip": "134.201.250.155",
"hostname": "134.201.250.155",
"type": "ipv4",
"continent_code": "NA",
"continent_name": "North America",
"country_code": "US",
"country_name": "United States",
"region_code": "CA",
"region_name": "California",
"city": "Los Angeles",
"zip": "90013",
"latitude": 34.0453,
"longitude": -118.2413
}
我正在寻找过去 2 周的解决方案。请任何人帮助我,这将不胜感激。提前致谢。
【问题讨论】:
-
请更具体一些“对我不起作用”是没有帮助的声明。编辑您的问题并尽可能准确地描述您面临的问题和错误。
-
可以添加错误日志吗?
-
我编辑并添加了更多信息。运行应用程序时我没有遇到任何错误。
-
由于你使用
json.optString("type"),如果响应JSON中没有类型键,它不会抛出任何异常,而是返回一个空字符串。所以,这里可能就是这种情况。尝试记录响应字符串并查看您的响应是否具有类型键。另外,如果您的回复是JSONObject,为什么不直接使用Volley 的JsonObjectRequest?
标签: android json android-volley