Skip to content
This repository has been archived by the owner on Sep 28, 2024. It is now read-only.

JsonModel

Edvin Syse edited this page May 29, 2016 · 11 revisions

WikiDocumentationJsonModel

JsonModel

The REST Client that comes with Tornado FX can convert data to and from the data types defined in javax.json. To facilitate converison between these JSON objects and your model objects, you can choose to implement the interface JsonModel and one or both of the functions updateModel and toJSON.

updateModel is called to convert a JSON object to your domain model. It receives a JSON object from which you can update the properties of your model object.

toJSON is called to convert your model object to a JSON payload. It receives a JsonBuilder where you can set the values of the model object.

class Person : JsonModel {
    var id by property<Int>()
    fun idProperty() = getProperty(Person::id)

    var firstName by property<String>()
    fun firstNameProperty() = getProperty(Person::firstName)

    var lastName by property<String>()
    fun lastNameProperty() = getProperty(Person::lastName)

    val phones = FXCollections.observableArrayList<Phone>()

    override fun updateModel(json: JsonObject) {
        with(json) {
            id = int("id")
            firstName = string("firstName")
            lastName = string("lastName")
            phones.setAll(getJsonArray("phones").toModel())
        }
    }

    override fun toJSON(json: JsonBuilder) {
        with(json) {
            add("id", id)
            add("firstName", firstName)
            add("lastName", lastName)
            add("phones", phones.toJSON())
        }
    }
}

class Phone : JsonModel {
    var id by property<Int>()
    fun idProperty() = getProperty(Phone::id)

    var number by property<String>()
    fun numberProperty() = getProperty(Phone::number)

    override fun updateModel(json: JsonObject) {
        with(json) {
            id = int("id")
            number = string("number")
        }
    }

    override fun toJSON(json: JsonBuilder) {
        with(json) {
            add("id", id)
            add("number", number)
        }
    }
}

JsonModel with getters/setters and property() accessor functions to be JavaFX Property compatible

When you implement JsonModel you also get the copy function for free, which creates a copy of your model object.

Tornado FX also comes with special support functions for reading and writing JSON properties. Please see the bottom of Json.kt for an exhaustive list.

The JsonBuilder is an abstraction over javax.json.JsonObjectBuilder that supports null values. Instead of blowing up, it silently dismisses the missing entry.

Next: Rest Client

Clone this wiki locally