-1
我想從JSONfile中讀取信息,我將在我的Android應用程序(我正在使用android studio)中使用它。看起來代碼能夠讀取並保存整個文件,但無法挑選出我想要的信息?這是我試圖讀取的JSON文件:http://www.ime.ntnu.no/api/course/tma4100。 誰能告訴我我做錯了什麼? Thankyou。使用ASYNC讀取JSON文件任務
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);
}
}
}