Skip to content

Gson

implementation("com.google.code.gson:gson:2.8.9")
data class Music(
val cover: String,
val title: String,
val url: String
) {
fun title(): String = title.replace(".mp3", "")
}

object : TypeToken<List<Music>>() {}.type (provided by gson) is for non-generic type

var data by remember { mutableStateOf<List<Music>>(emptyList()) }
withContext(Dispatchers.IO) {
val jsonString =
URL("https://skills-music-api.eliaschen.dev/music").openConnection().let {
BufferedReader(InputStreamReader(it.getInputStream()))
}.use { it.readText() }
val gson = Gson()
val jsonData = object : TypeToken<List<Music>>() {}.type
data = gson.fromJson(jsonString, jsonData)
}
if(data.isNotEmpty()){
LazyColumn {
items(data) {
Text(it.title())
}
}
}
data class Todo(
@SerializedName("user_id") val userId: Int,
@SerializedName("todo_id") val id: Int,
@SerializedName("task") val title: String,
@SerializedName("done") val completed: Boolean
)

Example: data.json located in assets/

{
"cities": [
{"name": "Taipei", "population": 2646204},
{"name": "Kaohsiung", "population": 2773496},
{"name": "Taichung", "population": 2815100}
]
}
data class City(val name: String, val population: Int)
data class CityList(val cities: List<City>)
val inputStream = context.assets.open("data.json").BufferReader.use {it.readText()}
val gson = Gson()
gson.fromJson(reader, CityList::class.java)