I'm trying to parse the following JSON File. It's on a different package and I'm trying to import it. I have tried installing different packages and adding dependencies on Gradle, but it seems unclear for me. Most of the tutorials have the folder assests where the json file is located or their version contains Java. Does anyone know how I can read the JSON file step by step with Kotlin on Android Studio?.
Asked
Active
Viewed 9,672 times
1 Answers
1
I don't think you can do that directly from another module but there is a way with which you can do that, follow the steps below:
Get
JSON
as aString
from theAssets
folder.fun readJSONFromAsset(): String? { var json: String? = null try { val inputStream:InputStream = assets.open("yourFile.json") json = inputStream.bufferedReader().use{it.readText()} } catch (ex: Exception) { ex.printStackTrace() return null } return json }
Parse that
JSON
withGson
.fun parseJSON() { Gson().fromJson(readJSONFromAsset(), YourObjectModel::class.java) }
Make a class in the
module
in whichJSON
is present and place the above methods in it.class FetchJSONFromModule() { companion object { fun readJSONFromAsset(): String? { var json: String? = null try { val inputStream:InputStream = assets.open("yourFile.json") json = inputStream.bufferedReader().use{it.readText()} } catch (ex: Exception) { ex.printStackTrace() return null } return json } fun parseJSON(): ObjectFromJson { return Gson().fromJson(readJSONFromAsset(), YourObjectModel::class.java) } } }
Import the module ( in which JSON and above class is present) in the module in which you want to use the JSON by adding the dependency below;
implementation project(":YourModuleName")
- Then call the class, in the class in which you want to use the
JSON
val data = FetchJSoNFromModule.parseJSON()

Himanshu Choudhary
- 360
- 1
- 8