将Kotlin数据类转换为JSON字符串。

20

我有一个数据类,其类定义如下

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个回答

21

我看到你想将 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"}]}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接