How to parse local JSON file in assets?

Viewed 28425

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.

4 Answers

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)

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();
Related