Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
Data class init function is not called when object generated from GSON in kotlin

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!