我正在尝试从JSON文件中读取信息,我将在我的Android应用程序中使用它(我使用的是android studio)。好像代码能够读取并保存整个文件,但是无法找到我想要的信息?这是我试图阅读的JSON文件:http://www.ime.ntnu.no/api/course/tma4100。 谁能告诉我我做错了什么? 谢谢。
public class JSONTask extends AsyncTask<String,String,String> {
private Fag nyttFag;
@Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
//read from API
InputStream stream = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
//Get objekt course from the whole API
JSONObject parentObject = new JSONObject(finalJson);
JSONObject course = parentObject.getJSONObject("course");
StringBuffer finalBufferedData = new StringBuffer();
//JSONObject finalObject = parentObject2.getJSONObject(0);
String coursename = course.getString("name");
String code = course.getString("code");
System.out.println(coursename);
finalBufferedData.append(code + "-" + coursename + "\n");
nyttFag = new Fag(code,coursename);
return finalBufferedData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
MainActivityProfessor.fagData.setText(result);
if (!navnPåFag.contains(nyttFag.name)) {
navnPåFag.add(nyttFag.name);
}
}
}
答案 0 :(得分:0)
你需要证明JSON正在被正确下载,我建议在线上进行一些调整:
JSONObject parentObject = new JSONObject(finalJson);
验证是否正确解析了 finalJson ,然后验证 course 变量是否真正成为JSONObject。