I'm learning Android development, trying to do cod...
# android
r
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
You cannot use AssetManager from JVM, on Android assets have to be loaded using context.getAssets(), just Google "reading assets android"
r
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
If it’s a simple JSON that’s part of your built app, put it in raw and use
openRawResource
. You’ll find examples online on how to read that out to an input stream. https://developer.android.com/reference/android/content/res/Resources#openRawResource(int,%20android.util.TypedValue)