10

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.

nicoqueijo
  • 872
  • 2
  • 11
  • 28
  • Possible duplicate of [How to parse JSON in Android](https://stackoverflow.com/questions/9605913/how-to-parse-json-in-android) – Fabien Jul 18 '17 at 21:00
  • Why does it matter *where* you get the JSON from? The tutorials are actually *getting a string*, and you create `new JSONObject(String)`... So, load the *assets File to a String* – OneCricketeer Jul 18 '17 at 21:14
  • @cricket_007 Sorry if noob question, but do you always need to convert the JSON file into a string and then parse the string? You can directly parse the JSON file? – nicoqueijo Jul 18 '17 at 21:16
  • It's understandable question :) You can parse an InputStream using `JsonReader` https://developer.android.com/reference/android/util/JsonReader.html – OneCricketeer Jul 18 '17 at 21:17

4 Answers4

39

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!

Syed Md. Kamruzzaman
  • 979
  • 1
  • 12
  • 33
faraz khonsari
  • 1,924
  • 1
  • 19
  • 27
8

Previous answers work well, but if you're using Kotlin you can do it in a very nice and concise way by using the classes in the kotlin.io package.

val objectArrayString: String = context.resources.openRawResource(R.raw.my_object).bufferedReader().use { it.readText() }
val objectArray = Gson().fromJson(objectArrayString, MyObject::class.java)

You could even turn into a nice generic extension method if you want for easy reuse:

inline fun <reified T> Context.jsonToClass(@RawRes resourceId: Int): T =
        Gson().fromJson(resources.openRawResource(resourceId).bufferedReader().use { it.readText() }, T::class.java)

Which you would then simply call like this:

context.jsonToClass<MyObject>(R.raw.my_object)
Casper
  • 471
  • 7
  • 12
2

first you need to read the json file from assets , you can use this method

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;

}

then

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));
}
Ali Faris
  • 17,754
  • 10
  • 45
  • 70
0

Put your json file in raw folder and whit Gson library you can pars json :

Reader reader= new InputStreamReader(getResources().openRawResource(R.raw.json_test));
JsonElement json=new Gson().fromJson(reader,JsonElement.class); 

You can use this JsonElemnt for Gson or if you want json as string you can do this :

String jsonString=json.toString();
mostafa3dmax
  • 997
  • 7
  • 18