How to generate JSON literal with Kotlin-Javascript

There are many existing javascript functions accept JSON as paramters.

With Kotlin-Javascript, how can I generate JSON literals? And how can I declare traits for those methods?

E.g. Following is an existing javascript function:

  function save(user) {
  }

  save({
  name : “Freewind”,
  age: 100
  });

In my Kotlin-javascript code:

  native fun save(user: ???) // what type?

  save( ??? ) // what should be here?

If you use Klaxon, it would look like this:

save(json {   obj("name", "freewind", "age", 100) })

The problem is that you save() method needs to accept the type that Klaxon returns for this (JsonObject).

It seems Klaxon can't work with Kotlin-javascript compiler. It invokes some java classes, which can be used to generate javascript source.

Yes, I know nothing about the Kotlin Javascript compiler. It would be nice to make Klaxon compatible with it but I have no idea what needs to be done right now.

Unfortunately right now you can't do it easily.

My solution:

``

native
class User {
  val name: String = js.noImpl
  val age: Int = js.noImpl
}

native(“Object”)
class MutableUser {
  var name: String = js.noImpl
  var age: Int = js.noImpl
}

fun User(name: String, age: Int): User {
  val user = MutableUser()
  user.name = name
  user.age = age
  return user as User
}

native fun save(user: User)

or just:

``

native(“Object”)
class User {
  var name: String = js.noImpl
  var age: Int = js.noImpl
}

fun User(name: String, age: Int): User {
  val user = User()
  user.name = name
  user.age = age
  return user
}

native fun save(user: User)

Another solution

You can declare class in JS:

``

function User(name, age) {
  this.name = name;
  this.age = age;
}

And write in Kotlin:

``

native class User(val name: String, val age: Int)
native fun save(user: User)

Thank you, this is the best solution so far.

I know this is an old question, but I thought I’d mention my solution: all my objects implement toJSON() metod, which returns their JSON representation, so in the case mentioned in this question User class in Kotlin would be:

class User(val name: String, val age: Int) {
   fun toJSON(): String {
      return "{\"name\": \"$name\", \"age\": $age}"
   }
}

and in JavaScript you would call:

var user = new module_name.package_name.User('forinil2', 15)
save(user.toJSON())

Can someone convert the code from native to the current external way of doing things? I’m a bit confused by some things like how to specify (“Object”) and js.noImpl