Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

211
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda