将Kotlin数据类转换为json字符串

时间:2019-07-09 23:37:41

标签: android json kotlin gson

我有一个具有此类定义的数据类

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"}]}

2 个答案:

答案 0 :(得分:0)

我看到您要序列化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"}]}

答案 1 :(得分:0)

Gson

Gson是一个Java库,可用于将Java对象转换为其JSON表示形式。它还可以用于将JSON字符串转换为等效的Java对象。 Gson可以处理任意Java对象,包括您没有源代码的现有对象。

如果您是serializing/deserializing的对象是ParameterizedType(即,至少包含一个类型参数,并且可能是数组),则必须使用toJson(Object, Type) or fromJson(String, Type)方法。这是一个对ParameterizedType进行序列化和反序列化的示例:

 Gson gson = new Gson(); // Or use new GsonBuilder().create();
 MyType target = new MyType();
 String json = gson.toJson(target); // serializes target to Json
 MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2

其他方式:

 Type listType = new TypeToken<List<String>>() {}.getType();
 List<String> target = new LinkedList<String>();
 target.add("blah");

 Gson gson = new Gson();
 String json = gson.toJson(target, listType);
 List<String> target2 = gson.fromJson(json, listType);