【发布时间】:2017-02-03 12:57:15
【问题描述】:
您好!在我删除硬编码的JSON 数据并移至从 URL 请求数据之后。我遇到异常错误。代码与最终的官方 git 几乎相同,但我得到了错误。
我从JSON 中提取数据的代码是:
private static final String USGS_REQUEST_URL =
"http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&orderby=time&minmag=5&limit=10";
//
public static List<Earthquake> extractFeaturesfromJson(String earthquakeJSON) {
/*if the json is null then return earlu*/
if (TextUtils.isEmpty(earthquakeJSON)) {
return null;
}
// Create an empty ArrayList that we can start adding earthquakes to
List<Earthquake> earthquakes = new ArrayList<>();
// Try to parse the JsonResponseString. If there's a problem with the way the JSON
// is formatted, a JSONException exception object will be thrown.
// Catch the exception so the app doesn't crash, and print the error message to the logs.
try {
// create an object form jsonString
JSONObject root = new JSONObject(earthquakeJSON);
JSONArray features = root.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
// Get a single earthquake at position i within the list of earthquakes
JSONObject currentEarthquake = features.getJSONObject(i);
// For a given earthquake, extract the JSONObject associated with the
// key called "properties", which represents a list of all properties
// for that earthquake.
JSONObject properties = currentEarthquake.getJSONObject("properties");
double mag = properties.getDouble("mag");
String location = properties.getString("place");
long time = properties.getLong("time");
//extract the value of key url
String url = properties.getString("url");
//create new object with magnitude, location ane time and url from json response
Earthquake earthquake = new Earthquake(mag, location, time, url);
earthquakes.add(earthquake);
}
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
}
// Return the list of earthquakes
return earthquakes;
}
logcat 显示:
09-26 14:49:23.628 2551-2584/com.example.android.quakereport E/com.example.android.quakereport.QueryUtils: Problem retrieving the earthquake JSON results.
【问题讨论】:
-
请提供您获得异常的日志
-
请发布错误日志、您正在解析的 JSON 数据以及您用于解析 JSON 的代码。
-
我看到你使用
Index 10 out of range [0..10)也许你使用for循环来获取对象?如果是真的,你应该检查你的循环索引。 -
1 - 未收到 JSON | 2 - JSON 与您的测试不同。