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 a String
from the Assets
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
with Gson
.
fun parseJSON() {
Gson().fromJson(readJSONFromAsset(), YourObjectModel::class.java)
}
Make a class in the module
in which JSON
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()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…