프로그래밍/android

[android] Kotlin ArrayList SharedPreferences json data (feat. Gson)

-샤리- 2021. 8. 24. 21:59

▣ Model

data class Person(val name: String, val age: Int)

 

▣ Read

val preferences = getSharedPreferences("pref", Context.MODE_PRIVATE)
val jsonData = preferences.getString("person", "")

val gson = Gson()
val token: TypeToken<MutableList<Person>> = object : TypeToken<MutableList<Person>>(){}
val list: MutableList<Person>? = gson.fromJson(jsonData, token.type)

 

▣ Write

val preferences = getSharedPreferences("pref", Context.MODE_PRIVATE)
val jsonData = preferences.getString("person", "")

val gson = Gson()
val token: TypeToken<MutableList<Person>> = object : TypeToken<MutableList<Person>>(){}
val list: MutableList<Person>? = gson.fromJson(jsonData, token.type)

list.add(Person("Tom", 20))
list.add(Person("Harry", 25))

val editor = preferences.edit()
editor.putString("person", gson.toJson(list, token.type))
editor.apply()