/** * Reads the JSON file and converts the JSON data to a {@link String}. * * @return A {@link String} representation of the JSON data. * @throws IOException if unable to read the JSON file. */private String readJsonDataFromFile() throws IOException {
InputStream inputStream = null; StringBuilder builder = new StringBuilder();
try {
String jsonDataString = null; inputStream = getResources().openRawResource(R.raw.menu_items_json); BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8")); while ((jsonDataString = bufferedReader.readLine()) != null) {
builder.append(jsonDataString); }
} finally {
if (inputStream != null) {
inputStream.close(); }
}
return new String(builder);}
/** * Adds {@link MenuItem}'s from a JSON file. */private void addMenuItemsFromJson() {
try {
String jsonDataString = readJsonDataFromFile(); JSONArray menuItemsJsonArray = new JSONArray(jsonDataString);
for (int i = 0; i < menuItemsJsonArray.length(); ++i) {
JSONObject menuItemObject = menuItemsJsonArray.getJSONObject(i);
String menuItemName = menuItemObject.getString("name"); String menuItemDescription = menuItemObject.getString("description"); String menuItemPrice = menuItemObject.getString("price"); String menuItemCategory = menuItemObject.getString("category"); String menuItemImageName = menuItemObject.getString("photo");
MenuItem menuItem = new MenuItem(menuItemName, menuItemDescription, menuItemPrice, menuItemCategory, menuItemImageName); mRecyclerViewItems.add(menuItem); }
} catch (IOException | JSONException exception) {
Log.e(MainActivity.class.getName(), "Unable to parse JSON file.", exception); }
}
댓글
댓글 쓰기