How to parse local JSON file in assets?

I have a JSON file in my resources folder. This file has one object with an array. The array has 150+ objects, each of which has three lines.

For each of these 150+ objects, I want to extract each line and create a java model object by passing three lines. All the tutorials that I find in Android JSON syntax extract JSON from a URL that I don't want to do.

+4
source share
2 answers

You should use the Gson library as a json parser .

add this dependency to the gradle application file:

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

raw res. json ( ). , json my_json.json

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

:

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

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

json :

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;
        }
    }

json :

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

json :

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

Json ! !

+9

json ,

public String readFile(String fileName) throws IOException
{
  BufferedReader reader = null;
  reader = new BufferedReader(new InputStreamReader(getAssets().open(fileName), "UTF-8")); 

  String content = "";
  String line;
  while ((line = reader.readLine()) != null) 
  {
     content = content + line
  }

  return content;

}

String jsonFileContent = readFile("json_in_assets.json");
JSONArray jsonArray = new JSONArray(jsonFileContent);
List<Person> persons = new ArrayList<>();
for (int i=0;i<jsonArray.length();i++)
{
  JSONObject jsonObj = jsonArray.getJSONObject(i);
  Integer id = jsonObj.getInt("id");
  String name = jsonObj.getString("name");
  String phone = jsonObj.getString("phone");
  persons.add(new Person(id , name , phone));
}
+1

Source: https://habr.com/ru/post/1681738/


All Articles