why Kotlin Object class to json object comes null?

Viewed 381

I am trying to convert kotlin object class using Gson() to JSON string but it gives back null where as object fields are actually holding the values. if it's a singleton object why can't I directly use to convert it in JSON string?

 val gson =  Gson()
 val dummy= Dummy
 val objDummy = gson.toJson(dummy)

object class:

object Dummy: Serializable{

   var test2: String? = "test2"

   var blank: String? = null

   var test1: String? = "test1"

}
2 Answers

Properties in object will be translated to static filds that are implicitly transient

You can use GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT) to allow Gson to serialize such filds.

val gson = GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create()
val dummy = Dummy
val objDummy = gson.toJson(dummy)

Also, it is pointless to use Serializable for object

oh i am even facing this problem. all you have to do is to install json to kotlin plugin from intellij idea plugin and i am sure it works fine and even works in nested json

Related