問候!在我刪除硬編碼的json數據並移動到從url請求數據之後。我有異常錯誤。代碼與最終的官方git非常相似,但是我收到了錯誤。解析json結果時出錯?
我從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.
請提供您得到的異常 – anddevmanu
請張貼錯誤的logcat日誌中,JSON數據你正在解析和你用來解析JSON的代碼。 –
我看到你使用'索引10超出範圍[0..10]'也許你用循環獲取對象?如果是這樣,你應該檢查你的循環索引。 – Numb