Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda