1

i'm trying to build a simple Android App with Jetpack Compose.

i want to load (JSON) data, stored on the assets folder

[ { "id": 1, "name": "Tiago" } ]

into a String in ViewModel. I'm trying the following

val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val jsonAdapter: JsonAdapter<User> = moshi.adapter(User::class.java)
val data = AssetManager.open("users.json").bufferedReader().use { it.readText() }
jsonAdapter.fromJson(data)
Code Poet
  • 6,222
  • 2
  • 29
  • 50
ROM
  • 91
  • 6
  • i decided to try Moshi library here is my current code (not working),\n val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build() val jsonAdapter: JsonAdapter = moshi.adapter(User::class.java) val data = AssetManager.open("users.json").bufferedReader().use { it.readText() } jsonAdapter.fromJson(data) – ROM Aug 03 '22 at 22:46
  • 1
    Post your code in your post. Not -unreadable- in a comment. – blackapps Aug 04 '22 at 04:25
  • You can search for reading json from assets. https://stackoverflow.com/questions/19945411/how-can-i-parse-a-local-json-file-from-assets-folder-into-a-listview – Thracian Aug 04 '22 at 06:04
  • @Thracian thanks for answering. Will investigate but the thread looks outdated. Im trying to do it, using Moshi in a Kotlin Jetpack Compose app. Loading JSON file in viewmodel, provide as Livedata to a composable function – ROM Aug 04 '22 at 09:09
  • The title of your question doesn't match the logic of the code you have. So do you want to get string from JSON file and save to LiveData or do you want to get string from JSON file and convert it to data class and save to LiveData? – Thales Isidoro Aug 04 '22 at 12:20
  • i want to load JSON file content on the assets folder (list of users, e.g. id + name+email) into a data object (user data class). I want to do in the viewmodel, provide the data to a jetpack composable (display it in a column). – ROM Aug 04 '22 at 15:38

0 Answers0