Khalil Khalil
Khalil Khalil

Reputation: 531

How get and use json from file with kotlin android?

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

Answers (2)

Artem Botnev
Artem Botnev

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

Achraf Amil
Achraf Amil

Reputation: 1375

The best way (IMHO) to read and write Json in Kotlin is Moshi:

  • Declare a data class for each data structure you have in your file (you can use the json keys as field names).
  • You might need to declare a global data class containing your data classes.
  • Build a moshi instance.
  • Get your data class moshi adapter.
  • Use it to read the file.

More about how to use Moshi: https://github.com/square/moshi

Upvotes: 0

Related Questions