JSON support using Jackson

预计阅读时间: 2 分钟

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

This feature is a ContentNegotiation converter.

本特性在构件 io.ktor:ktor-jackson:$ktor_version 中的 io.ktor.jackson.JacksonConverter 类中定义
dependencies { compile "io.ktor:ktor-jackson:$ktor_version" }
dependencies { compile("io.ktor:ktor-jackson:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-jackson</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

Basic usage

To install the feature by registering a JSON content convertor using Jackson:

install(ContentNegotiation) {
    jackson {
        // Configure Jackson's ObjectMapper here
    }
}

The jackson block is a convenient method for:

register(ContentType.Application.Json, JacksonConverter(ObjectMapper().apply {
    // ...
}.create()))

Configuration

Inside the jackson block, you have access to the ObjectMapper used to install the ContentNegotiation. To give you an idea of what is available:

install(ContentNegotiation) {
    jackson {
        enable(SerializationFeature.INDENT_OUTPUT)
        enable(...)
        dateFormat = DateFormat.getDateInstance()
        disableDefaultTyping()
        convertValue(..., ...)
        ...
    }
}