【发布时间】:2020-11-25 12:12:10
【问题描述】:
我想为我的应用程序获取 JSON 格式的数据,我尝试了不同的方法来解决这个问题,但是我在这个错误中找不到答案。我希望你们能帮助我,如果您需要更多详细信息,请告诉我。
这是我得到的错误:
E/MainActivity: Problem parsing the earthquake JSON results
org.json.JSONException: End of input at character 0 of
at org.json.JSONTokener.syntaxError(JSONTokener.java:460)
at org.json.JSONTokener.nextValue(JSONTokener.java:101)
at org.json.JSONObject.<init>(JSONObject.java:164)
at org.json.JSONObject.<init>(JSONObject.java:181)
at com.example.android.soonami.MainActivity$TsunamiAsyncTask.extractFeatureFromJson(MainActivity.java:207)
at com.example.android.soonami.MainActivity$TsunamiAsyncTask.doInBackground(MainActivity.java:121)
at com.example.android.soonami.MainActivity$TsunamiAsyncTask.doInBackground(MainActivity.java:104)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
提取json格式数据的方法:
private Event extractFeatureFromJson(String earthquakeJSON) {
try {
JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);
JSONArray featureArray = baseJsonResponse.getJSONArray("features");
// If there are results in the features array
if (featureArray.length() > 0) {
// Extract out the first feature (which is an earthquake)
JSONObject firstFeature = featureArray.getJSONObject(0);
JSONObject properties = firstFeature.getJSONObject("properties");
// Extract out the title, time, and tsunami values
String title = properties.getString("title");
long time = properties.getLong("time");
int tsunamiAlert = properties.getInt("tsunami");
// Create a new {@link Event} object
return new Event(title, time, tsunamiAlert);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return null;
}
将数据放入Event对象的方法:
@Override
protected Event doInBackground(URL... urls) {
// Create URL object
URL url = createUrl(USGS_REQUEST_URL);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = "";
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
// TODO Handle the IOException
e.printStackTrace();
}
// Extract relevant fields from the JSON response and create an {@link Event} object
Event earthquake = extractFeatureFromJson(jsonResponse);
// Return the {@link Event} object as the result fo the {@link TsunamiAsyncTask}
return earthquake;
}
【问题讨论】: