Gson
Dependencies
Section titled “Dependencies”implementation("com.google.code.gson:gson:2.8.9")Data class
Section titled “Data class”data class Music( val cover: String, val title: String, val url: String) { fun title(): String = title.replace(".mp3", "")}Fetch API with Gson
Section titled “Fetch API with Gson”
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)}Display the data
Section titled “Display the data”if(data.isNotEmpty()){ LazyColumn { items(data) { Text(it.title()) } }}Use @SerializedName for custom JSON keys
Section titled “Use @SerializedName for custom JSON keys”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)Local JSON file
Section titled “Local JSON file”Example: data.json located in assets/
{ "cities": [ {"name": "Taipei", "population": 2646204}, {"name": "Kaohsiung", "population": 2773496}, {"name": "Taichung", "population": 2815100} ]}Create a dataclass
Section titled “Create a dataclass”data class City(val name: String, val population: Int)data class CityList(val cities: List<City>)Parsing data into a list
Section titled “Parsing data into a list”val inputStream = context.assets.open("data.json").BufferReader.use {it.readText()}val gson = Gson()gson.fromJson(reader, CityList::class.java)