Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse local JSON file in assets?

I have a JSON file in my assets folder. That file has one object with an array. The array has 150+ objects with each having three strings.

For each of these 150+ objects I want to extract each string and create a java model object with it passing the three strings. All the tutorials I'm finding on android JSON parsing are fetching the JSON from a url which I don't want to do.

like image 1000
nicoqueijo Avatar asked Jul 18 '17 20:07

nicoqueijo


People also ask

How can I parse a local JSON file from assets folder into a listview?

Source code How to fetch Local Json from Assets folder This function returns JSON file into a string. After that parse it into JSONObject, Like:- JSONObject object = new JSONObject(loadJSONFile); Now access data acording to your json format.

What is in a JSON file?

What is a JSON file? A JSON file stores data in key-value pairs and arrays; the software it was made for then accesses the data. JSON allows developers to store various data types as human-readable code, with the keys serving as names and the values containing related data.


1 Answers

you should use Gson library as json parser.

add this dependency in app gradle file :

implementation 'com.google.code.gson:gson:2.8.1'

create raw folder in res folder. then copy your json file to raw folder.(its better to use raw folder instead of assets). for example you have this json file named my_json.json

{
  "list": [
    {
      "name": "Faraz Khonsari",
      "age": 24
    },
    {
      "name": "John Snow",
      "age": 28
    },
    {
      "name": "Alex Kindman",
      "age": 29
    }
  ]
} 

then create your model class:

public class MyModel {
        @SerializedName("list")
        public ArrayList<MyObject> list;

       static public class MyObject {
            @SerializedName("name")
            public String name;
            @SerializedName("age")
            public int age;
        }
    }

then you should create a function to read your json file :

public String inputStreamToString(InputStream inputStream) {
        try {
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, bytes.length);
            String json = new String(bytes);
            return json;
        } catch (IOException e) {
            return null;
        }
    }

then read your json file:

String myJson=inputStreamToString(mActivity.getResources().openRawResource(R.raw.my_json));

then convert json string to model:

MyModel myModel = new Gson().fromJson(myJson, MyModel.class);

now your Json have been converted to a model ! Congratulation!

like image 194
faraz khonsari Avatar answered Oct 24 '22 15:10

faraz khonsari