Android Parse JSON file from Assets

Intro

If you ever wondered how to read and parse a simple JSON file stored in the assets directory of your Android project, here is a way to do it.

Coding…

  1. Under src/main add new directory named “assets“.
  2. Inside this directory add your json file.
  3. Create a Utils class to add the method that will read your json file from assets.
import android.content.Context
import android.util.Log
import java.io.IOException

class Utils {
    fun getAssetJsonData(context: Context): String? {
        val json: String
        try {
            val inputStream = context.getAssets().open("properties.json")
            val size = inputStream.available()
            val buffer = ByteArray(size)
            inputStream.use { it.read(buffer) }

            json = String(buffer)
        } catch (ioException: IOException) {
            ioException.printStackTrace()
            return null
        }

        // print the data
        Log.i("data", json)

        return json
    }
}
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;

public class Utils {
    public static String getAssetJsonData(Context context) {
        String json;
        try {
            InputStream is = context.getAssets().open("properties.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;
        }
        Log.e("data", json);
        return json;
    }
}

Now in your activity you can parse the json file like this:

String data = getAssetJsonData(getApplicationContext());
Type type = new TypeToken<Your model class>(){}.getType();

Your Model class properties = new Gson().fromJson(data, type);

A concrete example is this:

json file

[
  {
    "name": "Temperature",
    "type": "Motor",
    "unit": "°C",
    "value": "40"
  },
  {
    "name": "Remaining capacity",
    "type": "Battery",
    "unit": "Wh",
    "value": "250"
  }
]
String data = getAssetJsonData(getApplicationContext());
Type type = new TypeToken<List<Property>>(){}.getType();
List<Property> properties = new Gson().fromJson(data, type);
Menu