Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data class init function is not called when object generated from GSON in kotlin [duplicate]

I'm using Gsson to convert JSON to Kotlin data class. While creating data class object I want to parse the value in init method. But init never called and generated object's values are null.

data class Configuration (val groupId:Int, val key:String, val source:String){
    val query:String
    val search:String
    init {
        val obj = JSONObject(key)
        query = obj.getString("q")
        search = obj.getString("search")
    }
}

When I got the object of Configuration from Gson, query and search value is always null and init block was never executed. I also tried constructor and without data keyword, results are same.

like image 613
shantanu Avatar asked Feb 03 '23 19:02

shantanu


1 Answers

init block is only executed when primary constructor is called. But gson doesn't call primary constructor when parsing json to object.

To solve this, I think, you should implement query and search as a get method or use lazy init. Something like this:

data class Configuration(val groupId: Int, val key: String, val source: String) {
    var query: String = ""
        get() {
            if (field == null) {
                initInternal()
            }
            return field
        }
        private set

    var search: String? = null
        get() {
            if (field == null) {
                initInternal()
            }
            return field
        }
        private set

    private fun initInternal() {
        val obj = JSONObject(key)
        query = obj.getString("q")
        search = obj.getString("search")
    }
}

or any other approach which will suite best to your requirements.

like image 176
Demigod Avatar answered Feb 06 '23 15:02

Demigod