I'm learning Android development, trying to do code a simple app in Kotlin. Want to load a JSON file on the assets folder into a string in ViewModel (livedata). Trying to use Moshi,
Copy code
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)
how to read the User.json in the assets folder into a string? then input the string into jsonAdapter.fromJson(string)?
😶 2
g
gildor
08/04/2022, 2:27 AM
You cannot use AssetManager from JVM, on Android assets have to be loaded using context.getAssets(), just Google "reading assets android"
r
Romão
08/04/2022, 9:19 AM
The examples on the web are old. How to do this "simple" task in 2022? Load a static JSON file using Kotlin in Jetpack Compose framework. This is a common action in iOS development for testing, mockup purpose. Can't find a example for Android Kotlin. Most cases assume remote loading (retrofit)
d
Daniel B Duval
08/04/2022, 4:28 PM
If it’s a simple JSON that’s part of your built app, put it in raw and use