本文主要是介绍gson的SerializedName与枚举类 (根据后台返回数据处理),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
示例一:
//后台字段枚举
enum class Day(val type: Int, val desc: String) {@SerializedName("1")MONDAY(1, "A"),@SerializedName("2")TUESDAY(2, "B"),@SerializedName("3")WEDNESDAY(3, "C"),@SerializedName("4")THURSDAY(4, "D"),@SerializedName("5")FRIDAY(5, "E"),@SerializedName("6")SATURDAY(6, "F"),@SerializedName("7")SUNDAY(7, "G")
}//后台数据
data class User(val name: String? = null,val day: Day = Day.FRIDAY
)//测试
fun main() {val gson = Gson()var user = User("xq", Day.WEDNESDAY)val userWithEnumJson = gson.toJson(user)println("生成json===========================================$userWithEnumJson")val userJson = "{\"name\":\'xq\',\"day\":5}"user = gson.fromJson(userJson, User::class.java)println("解析json===========================================${user}")println("解析json===========================================${user.day}")println("解析json===========================================${user?.day?.type}")println("解析json===========================================${user?.day?.desc}")
}
//生成json==========================================={"name":"xq","day":"3"}
//解析json===========================================User(name=xq, day=FRIDAY)
//解析json===========================================FRIDAY
//解析json===========================================5
//解析json===========================================E
示例二:
后台返回的枚举value值多样,我们可以自己定义多个数据
enum class City(val cityId: Int, val cityName: String) {A(11, "广州"),B(20, "深圳"),C(35, "佛山"),D(49, "东莞");
}private val list: List<City> = listOf(City.A,City.B,City.C,City.D
)@Test
fun test4() {list.forEach {println("${it.cityId}==========================${it.cityName}")}
}
@Test
fun test3() {val list: List<Map<Int, String>> = listOf(mapOf(11 to "广州"),mapOf(20 to "深圳"),mapOf(35 to "佛山"),mapOf(49 to "东莞"))list.forEach {for (en in it.entries) {println("${en.key}====================${en.value}")}}
}
@Test
fun test2() {data class StringArrayBean(val id: Int,val name: String)val list: List<StringArrayBean> = listOf(StringArrayBean(11, "广州"),StringArrayBean(20, "深圳"),StringArrayBean(35, "佛山"),StringArrayBean(49, "东莞"))list.forEach {println("${it.id}========================${it.name}")}
}
这篇关于gson的SerializedName与枚举类 (根据后台返回数据处理)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!