Android Parse JSON file from Assets

Android Parse JSON file from Assets

Under src/main add new directory named “assets“. Inside this directory add your json file.

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;
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);
,
Previous Post
Android Squared CardView

Related Posts

Menu