Ktor-Moshi
Ktor is a framework for building asynchronous servers and clients in connected systems. Ktor allows the application to decide how data should be serialized/deserialized when sent over the network.
Ktor-Moshi allows an application to use Moshi when dealing with JSON content.
Usage
Server
When implementing a server, the ContentNegotiation feature will convert the content. Bellow is an example of installing Moshi for content negotiation:
install(ContentNegotiation) {
moshi {
// Configure the Moshi.Builder here.
add(Date::class.java, Rfc3339DateJsonAdapter())
}
}
A Moshi.Builder is available inside the moshi
block if it needs to be customized. In this example, Moshi's pre-build RFC-3339 Date adapter is added.
Alternatively, if the application already has a Moshi
instance, it can be provided instead of creating a new one.
install(ContentNegotiation) {
moshi(myExistingMoshiInstance)
}
Refer to the ContentNegotiation documentation for information on how to send and receive formatted data.
Client
When implementing a client, the Json feature will convert the content. Bellow is an example of installing Moshi for serializing JSON content:
val client = HttpClient(HttpClientEngine) {
install(JsonFeature) {
serializer = MoshiSerializer {
add(Rfc3339DateJsonAdapter())
}
}
}
A Moshi.Builder is available inside the MoshiSerializer
block if it needs to be customized. In this example, Moshi's pre-build RFC-3339 Date adapter is added.
Alternatively, if the application already has a Moshi
instance, it can be provided instead of creating a new one.
val client = HttpClient(HttpClientEngine) {
install(JsonFeature) {
serializer = MoshiSerializer(myExistingMoshiInstance)
}
}
Refer to the Client documentation for information on how to send and receive formatted data.
Download
Each component (server & client) are published as independent packages.
Add a gradle dependency to your project:
- Server:
implementation 'com.hypercubetools:ktor-moshi-server:LATEST_VERSION'
- Client:
implementation 'com.hypercubetools:ktor-moshi-client:LATEST_VERSION'
Fork
Ryan Harter's ktor-moshi
is the original source for this project. The project has been expanded since it's initial state.