2

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"

}
003
  • 197
  • 1
  • 12

2 Answers2

3

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

IR42
  • 8,587
  • 2
  • 23
  • 34
  • 1
    do you think, storing data in singleton object class and then use that directly to send it as JSON is a good way? – 003 May 13 '20 at 18:50
0

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

  • 1
    I guess you miss understood the question. My question is on converting from kotlin object to json. – 003 May 13 '20 at 19:44