我需要从JSON网址检索一些值。下面的代码我尝试过,但是它没有给出任何错误或异常,但没有获取值。
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周内的解决方案。请任何人对此帮助我,将不胜感激。提前致谢。
答案 0 :(得分:0)
尝试JSONobject
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
}
/* try this instead */
JSONObject json = new JSONObject(response);
String cityName = json.getString("city");
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
txtJson.setText("That didn't work!");
}
});
queue.add(stringRequest);
答案 1 :(得分:0)
尝试下面的代码
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);
if (json.has("type") && !json.isNull("type")) {
String cityName = json.getString("type");
txtJson.setText(cityName);
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("errror",e.toString());// Not getting any error
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
txtJson.setText("That didn't work!");
}
});
queue.add(stringRequest);