로컬에 저장된 Json파일로부터 데이터읽어오기(String으로 변환), 그리고 Array(JsonArray)에 저장하기

/** * 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);    }
}

댓글

이 블로그의 인기 게시물

API 요청 URL(URI) 만들기(조합하기) -Uri.Builder사용하기-

TextView에 글자를 넣어주는 방법(setText, append)

텍스트 뷰의 배경을 원형 이미지로 지정하고, 배경 색상 채우기(안드로이드)