Skip to content

Ktor feature that adds Moshi JSON serialization support

License

Notifications You must be signed in to change notification settings

rharter/ktor-moshi

Repository files navigation

Ktor: Moshi

The Moshi feature allows you to handle JSON content in your application easily using the Moshi library.

This feature provides a ContentNegotiation converter.

Usage

Install the feature by registering a JSON content converter using Moshi:

install(ContentNegotiation) {
  moshi {
    // Configure the Moshi.Builder here.
    add(Date::class.java, Rfc3339DateJsonAdapter())
  }
}

Inside the moshi block you have access to the Moshi.Builder, which you can configure as needed for your application.

If you already have an instance of Moshi you can simply provide that and it will be used, instead of creating a new one.

install(ContentNegotiation) {
  moshi(myInjectedMoshi)
}

Once the Moshi converter is installed you use it like you would any other ContentNegotiation converter, by using call.respond(myObject) and call.receive<MyType>().

routing {
  get("/") {
    // Simply pass an object to `call.respond` and it will be
    // converted to JSON if the client accepts `application/json`
    val myResponseObject = ...
    call.respond(myResponseObject)
  }
  post("/") {
    // Use `call.receive` to get the JSON request as a
    // deserialized object.
    val request = call.receive<MyRequestObject>()
    ...
  }
}

Download

Add a gradle dependency to your project:

compile 'com.ryanharter.ktor:ktor-moshi:1.0.1'

Snapshots of the latest development version are available in Sonatype's snapshots repository.

License

Copyright 2018 Ryan Harter.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

About

Ktor feature that adds Moshi JSON serialization support

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages