info@androidpaper.co.in

How to Parse Local JSON from Assets in Android

Parsing local JSON files in Android is a common task when you want to retrieve data stored in a JSON format from your app's assets folder. JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read and write. Parsing a local JSON file involves reading the file from the assets folder, extracting the data from the JSON structure, and using it in your Android application. This process typically involves the following steps:

Step 1: Copy the JSON file to the assets folder Copy the JSON file you want to parse into the assets folder of your Android project. If the assets folder doesn't exist, create it under the main folder of your project. Step 2: Read the JSON file To read the JSON file from the assets folder, you can use the AssetManager class. In your activity or fragment, obtain an instance of AssetManager using the getAssets() method:

 InputStream is = getApplicationContext().getAssets().open("file.json");

Step 3: Read the JSON file content Using the AssetManager, open an input stream to the JSON file and read its content as a String:

 public String loadJSONFromAsset() {
        String json = null;
        try {
            InputStream is = getApplicationContext().getAssets().open("file.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }

Make sure to replace "file.json" with the actual path and filename of your JSON file. Step 4: Parse the JSON data Once you have the JSON content as a String, you can parse it using any JSON parsing library. In this example, we'll use the built-in JSONObject and JSONArray classes:

try {
            JSONArray jsonarray = new JSONArray(loadJSONFromAsset());
            for (int i = 0; i < jsonarray.length(); i++) {
                JSONObject jsonobject = jsonarray.getJSONObject(i);
                nname = jsonobject.getString("st");
                des = jsonobject.getString("s");


                ListItem listItem = new ListItem();
                listItem.setTitle(nname);
                listItem.setDescription(des);
                titlelist.add(listItem);

            }

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

To work with this, we need object class.

public class ListItem {
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    String title;
    String id;
    String description;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }


}

For Adapter Class;

public class ListviewAdapter extends BaseAdapter {
    ArrayList<ListItem> titlelist= null;
    Context context;
    LayoutInflater inflater;
    String id,title;
    TextView tv_title;

    public ListviewAdapter(Context context, ArrayList<ListItem> array) {
        this.context= context;
        this.titlelist = array;
    }

    @Override
    public int getCount() {
        return titlelist.size();
    }

    @Override
    public Object getItem(int position) {
        return titlelist.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // inflater = ((Activity) context).getLayoutInflater();
        View row = convertView;
        row = LayoutInflater.from(context)
                .inflate(R.layout.row_item, parent, false);
        tv_title = (TextView) row.findViewById(R.id.tv_title);

        tv_title.setText(titlelist.get (position).getTitle ());
        id = titlelist.get(position).getId();
        title = titlelist.get (position).getTitle ();
   

//        String descr = titlelist.get(position).getDefinition();
//        Log.i("descr", descr);
        return row;
    }
}

Another Written Description

In Main Activity.

public class MainActivity extends AppCompatActivity {

    ListView lv;
    List<ListItem> titlelist = null;
    ListviewAdapter listviewAdapter;
    String nname, des;
    InterstitialAd mInterstitialAd;


    private static int TIME_OUT = 5000;

    ListItem clickeditemvalue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        ActionBar actionBar=getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
       //showFullAd();
        AdView mAdView = (AdView) findViewById(R.id.topad);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        loadInterstitialAd();

        ListView lv = (ListView) findViewById(R.id.lv);

        titlelist = new ArrayList<ListItem>();
        listviewAdapter = new ListviewAdapter(getApplicationContext(), (ArrayList<ListItem>) titlelist);
        lv.setAdapter(listviewAdapter);

        try {
            JSONArray jsonarray = new JSONArray(loadJSONFromAsset());
            for (int i = 0; i < jsonarray.length(); i++) {
                JSONObject jsonobject = jsonarray.getJSONObject(i);
                nname = jsonobject.getString("st");
                des = jsonobject.getString("s");


                ListItem listItem = new ListItem();
                listItem.setTitle(nname);
                listItem.setDescription(des);
                titlelist.add(listItem);

            }

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


       
    }
    public String loadJSONFromAsset() {
        String json = null;
        try {
            InputStream is = getApplicationContext().getAssets().open("file.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }

    public boolean onSupportNavigateUp() {
        Intent intent = new Intent(ListActivityThree.this, AllBasicActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
        return false;
    }
   
    
}

Step 5: Handle exceptions and errors It's important to handle exceptions that may occur during the JSON parsing process or while reading the file. Consider implementing appropriate error handling and logging to ensure your application behaves correctly. That's it! You have successfully parsed the local JSON file from the assets folder in Android. You can now use the extracted data as needed in your application.