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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With