Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Realm kotlin json to model

I have this json data and I want to convert it to Realm model:

{
"_id": "63dceb34a8c4bbeee1c807f9",
"weeks": [2, 3, 2, 3],
}

and this is my kotlin model:

open class ProgramDoc() : RealmObject {
    @PrimaryKey
    var _id: String = "",
    var weeks: RealmList<Int> = realmListOf<Int>()

}

But I got this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ProgramDoc.sessionPerWeek has type io.realm.kotlin.types.RealmList, got java.util.ArrayList

Any help please.

>Solution :

The problem here is that in your JSON data contains an ArrayList but your Realm model is expecting a RealmList.

What you can do is convert the ArrayList to a RealmList before mapping it to your Realm model.

open class ProgramDoc : RealmObject() {
    @PrimaryKey
    var _id: String = ""
    var weeks: RealmList<Int> = RealmList()
}

Example of how to get ProgramDoc model from a json :

val jsonObject = JSONObject(YOUR_JSON_HERE)

val programDoc = ProgramDoc(
    _id = jsonObject.getString("_id"),
    weeks = RealmList(jsonObject.getJSONArray("weeks").toList().map { it as Int })
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading