Reputation: 531
I have tried to get and use json from file in Kotlin-lang in Android but this is not so easy as I thought!
I have this data in json file:
[{
"place" : {
"place": "Hamburg Germany",
"lat" : 53.551142,
"lng" : 9.992291
},
"text": [
true, true, true, true, true
],
"language":{
"english": true,
"arabic": false,
"persian": false,
"turkish": false
}
}]
I need only get place data/information from file.
Does anyone know how to do this solution?
Upvotes: 0
Views: 8978
Reputation: 2427
Place your json file under assets folder and read this as a String
.
First, we need to create an extension to read the file. This extension takes file name as input.
fun AssetManager.readFile(fileName: String) = open(fileName)
.bufferedReader()
.use { it.readText() }
Now, use the extension to read the file as a String
.
val jsonString = context.assets.readFile("file_name.json")
For more details you can look at this: https://github.com/ArtemBotnev/TelegramCharts/blob/master/app/src/main/java/ru/artembotnev/telegramcompetition/Repository.kt
Upvotes: 4
Reputation: 1375
The best way (IMHO) to read and write Json in Kotlin is Moshi:
More about how to use Moshi: https://github.com/square/moshi
Upvotes: 0