Ktor Server 中的內容協商與序列化
必要的相依性:io.ktor:ktor-server-content-negotiation
程式碼範例: json-kotlinx
原生伺服器Ktor 支援 Kotlin/Native,可讓您在無需額外執行階段或虛擬機的情況下執行伺服器。支援:✅
ContentNegotiation 外掛程式有兩個主要用途:
- 在用戶端與伺服器之間協商媒體類型。為此,它使用
Accept與Content-Type標頭。 - 以特定格式序列化/反序列化內容。Ktor 開箱即用支援以下格式:JSON、XML、CBOR 和 ProtoBuf。
在用戶端上,Ktor 提供了 ContentNegotiation 外掛程式用於序列化/反序列化內容。
新增相依性
ContentNegotiation
若要使用 ContentNegotiation,請在建置指令碼中新增 ktor-server-content-negotiation 構件:
implementation(ktorLibs.server.contentNegotiation)implementation ktorLibs.server.contentNegotiation<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-server-content-negotiation-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>請注意,特定格式的序列化程式需要額外的構件。例如,kotlinx.serialization 針對 JSON 需要 ktor-serialization-kotlinx-json 相依性。
序列化
在使用 kotlinx.serialization 轉換器之前,你需要按照 Setup 區段中的說明新增 Kotlin 序列化外掛程式。
JSON
若要序列化/反序列化 JSON 資料,你可以選擇以下程式庫之一:kotlinx.serialization、Gson 或 Jackson。
在建置指令碼中新增 ktor-serialization-kotlinx-json 構件:
implementation(ktorLibs.serialization.kotlinx.json)implementation ktorLibs.serialization.kotlinx.json<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-serialization-kotlinx-json-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>在建置指令碼中新增 ktor-serialization-gson 構件:
implementation(ktorLibs.serialization.gson)implementation ktorLibs.serialization.gson<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-serialization-gson-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>在建置指令碼中新增 ktor-serialization-jackson 構件:
implementation(ktorLibs.serialization.jackson)implementation ktorLibs.serialization.jackson<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-serialization-jackson-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>XML
若要序列化/反序列化 XML,請在建置指令碼中新增 ktor-serialization-kotlinx-xml:
implementation(ktorLibs.serialization.kotlinx.xml)implementation ktorLibs.serialization.kotlinx.xml<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-serialization-kotlinx-xml-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>CBOR
若要序列化/反序列化 CBOR,請在建置指令碼中新增 ktor-serialization-kotlinx-cbor:
implementation(ktorLibs.serialization.kotlinx.cbor)implementation ktorLibs.serialization.kotlinx.cbor<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-serialization-kotlinx-cbor-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>ProtoBuf
若要序列化/反序列化 ProtoBuf,請在建置指令碼中新增 ktor-serialization-kotlinx-protobuf:
implementation(ktorLibs.serialization.kotlinx.protobuf)implementation ktorLibs.serialization.kotlinx.protobuf<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-serialization-kotlinx-protobuf-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>安裝 ContentNegotiation
若要將 ContentNegotiation 外掛程式安裝至你的應用程式中,請將其傳遞給指定 模組模組可讓您透過對路由進行分組來建構應用程式。 中的 install 函式。以下範例示範如何安裝 ContentNegotiation:
- 在
embeddedServer()函式呼叫中。 - 在
Application類別上明確定義的module()擴充函式中。
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
fun main() {
embeddedServer(Netty, port = 8080) {
install(ContentNegotiation)
// ...
}.start(wait = true)
}import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
// ...
fun Application.module() {
install(ContentNegotiation)
// ...
}設定序列化程式
Ktor 開箱即用支援以下格式:JSON、XML、CBOR。你也可以實作自己的自訂序列化程式。
JSON 序列化程式
若要在你的應用程式中註冊 JSON 序列化程式,請呼叫 json 方法:
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
install(ContentNegotiation) {
json()
}json 方法還允許你調整 JsonBuilder 提供的序列化設定,例如:
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = true
})若要在你的應用程式中註冊 Gson 序列化程式,請呼叫 gson 方法:
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.gson.*
install(ContentNegotiation) {
gson()
}gson 方法還允許你調整 GsonBuilder 提供的序列化設定,例如:
install(ContentNegotiation) {
gson {
registerTypeAdapter(LocalDate::class.java, LocalDateAdapter())
setDateFormat(DateFormat.LONG, DateFormat.SHORT)
setPrettyPrinting()
}若要在你的應用程式中註冊 Jackson 序列化程式,請呼叫 jackson 方法:
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.jackson.*
install(ContentNegotiation) {
jackson()
}jackson 方法還允許你調整 ObjectMapper 提供的序列化設定,例如:
install(ContentNegotiation) {
jackson {
configure(SerializationFeature.INDENT_OUTPUT, true)
setDefaultPrettyPrinter(DefaultPrettyPrinter().apply {
indentArraysWith(DefaultPrettyPrinter.FixedSpaceIndenter.instance)
indentObjectsWith(DefaultIndenter(" ", "\n"))
})
registerModule(JavaTimeModule()) // 支援 java.time.* 型別
}
}XML 序列化程式
若要在你的應用程式中註冊 XML 序列化程式,請呼叫 xml 方法:
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.xml.*
install(ContentNegotiation) {
xml()
}xml 方法還允許你存取 XML 序列化設定,例如:
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.xml.*
import nl.adaptivity.xmlutil.*
import nl.adaptivity.xmlutil.serialization.*
install(ContentNegotiation) {
xml(format = XML {
xmlDeclMode = XmlDeclMode.Charset
})
}CBOR 序列化程式
若要在你的應用程式中註冊 CBOR 序列化程式,請呼叫 cbor 方法:
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.cbor.*
install(ContentNegotiation) {
cbor()
}cbor 方法還允許你存取 CborBuilder 提供的 CBOR 序列化設定,例如:
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.cbor.*
import kotlinx.serialization.cbor.*
install(ContentNegotiation) {
cbor(Cbor {
ignoreUnknownKeys = true
})
}ProtoBuf 序列化程式
若要在你的應用程式中註冊 ProtoBuf 序列化程式,請呼叫 protobuf 方法:
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.protobuf.*
install(ContentNegotiation) {
protobuf()
}protobuf 方法還允許你存取 ProtoBufBuilder 提供的 ProtoBuf 序列化設定,例如:
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.protobuf.*
import kotlinx.serialization.protobuf.*
install(ContentNegotiation) {
protobuf(ProtoBuf {
encodeDefaults = true
})
}自訂序列化程式
若要為指定的 Content-Type 註冊自訂序列化程式,你需要呼叫 register 方法。在以下範例中,註冊了兩個自訂序列化程式來反序列化 application/json 與 application/xml 資料:
install(ContentNegotiation) {
register(ContentType.Application.Json, CustomJsonConverter())
register(ContentType.Application.Xml, CustomXmlConverter())
}接收與傳送資料
建立資料類別
若要將接收到的資料反序列化為物件,你需要建立一個資料類別,例如:
data class Customer(val id: Int, val firstName: String, val lastName: String)如果你使用 kotlinx.serialization,請確保該類別帶有 @Serializable 註解:
import kotlinx.serialization.*
@Serializable
data class Customer(val id: Int, val firstName: String, val lastName: String)kotlinx.serialization 程式庫支援以下型別的序列化/反序列化:
接收資料
若要接收並轉換請求的內容,請呼叫以資料類別作為參數的 receive 方法:
post("/customer") {
val customer = call.receive<Customer>()
customerStorage.add(customer)
call.respondText("Customer stored correctly", status = HttpStatusCode.Created)請求的 Content-Type 將用於選擇處理該請求的序列化程式。以下範例顯示了一個範例 HTTP 用戶端請求,其中包含在伺服器端轉換為 Customer 物件的 JSON 或 XML 資料:
POST http://0.0.0.0:8080/customer
Content-Type: application/json
{
"id": 3,
"firstName": "Jet",
"lastName": "Brains"
}POST http://0.0.0.0:8080/customer
Content-Type: application/xml
<Customer id="3" firstName="Jet" lastName="Brains"/>你可以在此處找到完整範例:json-kotlinx。
傳送資料
若要在回應中傳遞資料物件,你可以使用 respond 方法:
routing {
get("/customer/{id}") {
val id: Int by call.parameters
val customer: Customer = customerStorage.find { it.id == id }!!
call.respond(customer)在這種情況下,Ktor 會使用 Accept 標頭來選擇所需的序列化程式。你可以在此處找到完整範例:json-kotlinx。
實作自訂序列化程式
在 Ktor 中,你可以撰寫自己的序列化程式來序列化/反序列化資料。為此,你需要實作 ContentConverter 介面:
interface ContentConverter {
suspend fun serialize(contentType: ContentType, charset: Charset, typeInfo: TypeInfo, value: Any): OutgoingContent?
suspend fun deserialize(charset: Charset, typeInfo: TypeInfo, content: ByteReadChannel): Any?
}請參考 GsonConverter 類別作為實作範例。
