How to Parse a JSON File from the Assets Folder in Android

From WikiHTP

Nowadays, Usage of JSON in Android is typically increasing. Here we are going to discuss how to read a JSON file from the assets folder in android

Get the JSON from Asset[edit]

Consider we are having json file student_rank.json like this:

{
  "student" : 
  [ 
    {
      "name" : "Peter",
      "rank": 17,
      "age" : 12
    },
    {
      "name" : "John",
      "rank": 19,
      "age" : 12
    },
    {
      "name" : "Tony",
      "rank": 7,
      "age" : 13
    }
  ]
}

Save that student_rank.json in a assets folder /assets/student_rank.json. If you haven't created an assets folder yet see how to create an assets folder in android. Then parse that JSON file using getJSON() function.

    private String getJSON() {
        String json = null;
        try {
            InputStream ist = getActivity().getAssets().open("student_rank.json");
            int size = ist.available();
            byte[] buffer = new byte[size];
            ist.read(buffer);
            ist.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }

The above getJson() function reads the JSON file and converts that into a JSON string.

Parsing JSON in Android[edit]

    private void parseJson() {
        try {
            JSONObject obj = new JSONObject(getJSON());
            JSONArray m_jArry = obj.getJSONArray("student");
            for (int i = 0; i < m_jArry.length(); i++) {
                JSONObject hit = m_jArry.getJSONObject(i);
                String name = hit.getString("name");
                int rank = hit.getInt("rank");
                int age = hit.getInt("age");

                // so you can get that json values.

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

parseJson() function converts the json string into JSONObject then converts that into JSONArray. using for loop you can get the values of json.

About This Tutorial

This page was last edited on 4 February 2019, at 22:04.