将kotlin数据类转换为json字符串
Posted
技术标签:
【中文标题】将kotlin数据类转换为json字符串【英文标题】:convert kotlin data class into json string 【发布时间】:2019-11-19 13:10:01 【问题描述】:我有一个具有此类定义的数据类
data class AccountInfoResponse(
@SerializedName("userprofile") val userprofiles: ArrayList<UserProfile>,
@SerializedName("userpatients") val userpatients: ArrayList<UserPatient>
)
class UserPatient (
@SerializedName("sex") val sex: String,
@SerializedName("date of birth") val date_of_birth: String,
@SerializedName("address") val address: String,
@SerializedName("patientID") val patientId: Int,
@SerializedName("first name") val first_name: String,
@SerializedName("clinicName") val clinic_name: String,
@SerializedName("clinicID") val clinicId: Int,
@SerializedName("mobile") val mobile: String,
@SerializedName("last name") val last_name: String
)
我需要把这个类转换成这样的json字符串
"userpatients":["sex":"male","date of birth":"2010-01-03","image":"","clinics":[1],"primary_provider":["clinic":1,"patient":1,"providers":1],"role":"patient","last name":"John","address":"300 east main st. San Jose, Ca 95014","first name":"John","username":"John","email":"sameh88@ensofia.com","mobile":"+88083918427"],"userpatients":["sex":"female","date of birth":"2000-01-01","address":"fawal st1","patientID":1,"first name":"john","clinicName":"light house peds","clinicID":1,"mobile":"8056688042","last name":"john"]
【问题讨论】:
【参考方案1】:我可以看到你想序列化ArrayList<UserPatient>
。您可以使用Gson
轻松完成。
例子:
val response = AccountInfoResponse(/* Here goes the objects that is needed to create instance of this class */)
val jsonString = Gson().toJson(response.userpatients)
输出:
"userpatients":["sex":"male","date of birth":"2010-01-03","image":"","clinics":[1],"primary_provider":["clinic":1,"patient":1,"providers":1],"role":"patient","last name":"John","address":"300 east main st. San Jose, Ca 95014","first name":"John","username":"John","email":"sameh88@ensofia.com","mobile":"+88083918427"],"userpatients":["sex":"female","date of birth":"2000-01-01","address":"fawal st1","patientID":1,"first name":"john","clinicName":"light house peds","clinicID":1,"mobile":"8056688042","last name":"john"]
【讨论】:
以上是关于将kotlin数据类转换为json字符串的主要内容,如果未能解决你的问题,请参考以下文章
Kotlin 使用 Gson 将 json 字符串转换为对象列表
如何在 Kotlin 中将字符串数组 JSON 转换为 ArrayList?
Android -------- kotlin插件神器Json直接生成javaBean