我一直在搜索整夜,但找不到任何適合我的東西。如何從Java中的JSON文件中讀取
我想讀取和解析Java中的JSON文件。我嘗試了我找到的每個代碼,但都沒有爲我工作。我非常感謝你的幫助。
所以這裏的代碼:
public void parseJSONData() {
clearData();
try {
FileInputStream in = openFileInput(getFilesDir()
+ "/tbl_category.json");
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
我使用getFilesDir()+ 「/tbl_category.json」,因爲應用程序下載some.json文件中/data/data/com.the.restaurant/文件/何時開始。
而這裏的類代碼的其餘部分:
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(line);
JSONArray data = json.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject category = object.getJSONObject("Category");
Category_ID.add(Long.parseLong(category
.getString("Category_ID")));
Category_name.add(category.getString("Category_name"));
Category_image.add(category.getString("Category_image"));
Log.d("Category name", Category_name.get(i));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我剛開始學習Java,我會最非常感謝您的幫助!
更具體。什麼不行,發生了什麼,會發生什麼? –
問題是......在哪裏?什麼是不工作? –
更改JSONObject json = new JSONObject(line);到JSONObject json = new JSONObject(sb.toString()); – Divers