Milan Smolík
Milan Smolík

Reputation: 149

How to change a JSON value in Kotlin

I have a jsObject that looks like this {"Name": "Milan", "Surname": "Smolik"} hardcoded somewhere else in app and parsed with this library. When I println(fullName), I get {"name": "Milan", "surname": "Smolik"}.

Now, I would like to modify Name to Martin. How do I do that?

In JavaScript I would either fullName.name = 'Martin' or newName = {...fullName, name: 'Martin'}. Can I do that in Kotlin? Is there some library that would support modifying JSONs / JSON spread operator?

Upvotes: 0

Views: 8170

Answers (2)

SadeghAlavizadeh
SadeghAlavizadeh

Reputation: 607

you can't do it on the fly, you must map JSON into a data class and change any field you want in it and convert it to JSON again.

First create a data class:

data class YourModel(
  val Name: String,
  val Surname: String
) 

Use GSON to convert JSON to object like as below:

var yourModel = gson.fromJson(yourJsonString, YourModel::class.java)

and then change any field you want like as below:

yourModel.Name = "Martin"

finally you can convert it to JSON string again:

var jsonString = gson.toJson(yourModel)

Upvotes: 1

madhead
madhead

Reputation: 33422

Kotlin JS objects are dynamic, i.e. it is allowed to call any property or function with any parameters on a dynamic variable. So, just do obj.Name = "Martin" and it should work:

fun main() {
    val obj = js("{'Name': 'Milan', 'Surname': 'Smolik'}")

    obj.Name = "Martin"

    println(JSON.stringify(obj))
}

A link to playground.

Upvotes: 1

Related Questions