3

Previously, I asked this question: Implementing generic method in interface that uses implementors class which allowed for an object to be converted to a JSON string.

But, now I would like to reverse the process. Ideally this would look like:

interface Domain {
    constructor(json: String) {
        /*...*/
    }
}

@Serializable
class User(val a: Int, val b: Int): Domain {}

val user = User("{a: 3, b: 4}")

But, I'm unable to figure out how to construct an object directly from a JSON string.

A next best option would be create a static generator method:

interface Domain {
    companion object {
        inline fun <reified T> fromJSON(json: String): T {
            return Json.decodeFromString(json)
        }
    }
}

val user = User.fromJSON("{a: 3, b: 4}")

But, this doesn't work at all because User does not inherit Domain's companion object. The 3rd best option:

val user = Domain.fromJSON<User>("{a: 3, b: 4}")

This does work from the Android side, however since fromJSON is declared inline and reified it is not exposed to iOS at all from the KMM.

Which brings me to my current solution:

@Serializable
class User(val a: Int, val b: Int): Domain {
    companion object {
        fun fromJSON(json: String): User { return Json.decodeFromString(json) }
    }
}

val user = User.fromJSON("{a: 3, b: 4}")

This works, however it requires the above boilerplate code to be added to each and every 'Domain' object.

Is there anyway to improve on my current solution? (Of course, the higher up the chain the better.)

aepryus
  • 4,715
  • 5
  • 28
  • 41

1 Answers1

-1

I think you have Object then you should need to convert it as :--

  import com.google.gson.Gson
  import com.google.gson.GsonBuilder

  import com.codewithfun.kotlin.jsonparser.models.Tutorial

  fun main(args: Array<String>) {
  val gson = Gson()
  val gsonPretty = GsonBuilder().setPrettyPrinting().create()

  val tutsList: List<Tutorial> = listOf(
    Tutorial("Tut #1", "bezkoder", listOf("cat1", "cat2")),
    Tutorial("Tut #2", "zkoder", listOf("cat3", "cat4"))
    );

  val jsonTutsList: String = gson.toJson(tutsList)
 println(jsonTutsList)

 val jsonTutsListPretty: String = gsonPretty.toJson(tutsList)
 println(jsonTutsListPretty)
 }

Then the output be like :--

   [{"title":"Tut #1","author":"bezkoder","categories":["cat1","cat2"]},{"title":"Tut #2","author":"zkoder","categories":["cat3","cat4"]}]
[
  {
    "title": "Tut #1",
    "author": "bezkoder",
    "categories": [
      "cat1",
      "cat2"
    ]
  },
  {
    "title": "Tut #2",
    "author": "zkoder",
    "categories": [
      "cat3",
      "cat4"
    ]
  }
]
Laxmi kant
  • 128
  • 1
  • 11