docs(lesson6): clarify JSON auto-conversion with ContentNegotiation plugin
This commit is contained in:
1 parent
b9e621c9e0
commit
c089f2179e
1 file changed
+20
-1
@@ -72,8 +72,27 @@ Android 侧引擎(`shared/androidMain`)需要:
|
||||
### 2. Ktor 官方文档(课堂可直接贴)
|
||||
- Ktor Multiplatform Client 官方教程:
|
||||
`https://ktor.io/docs/client-create-multiplatform-application.html`
|
||||
- Ktor Serialization 官方说明(ContentNegotiation/JSON 的用途):
|
||||
`https://ktor.io/docs/server-serialization.html`
|
||||
|
||||
### 3. 为什么是 `libs.ktor.client.content.negotiation`?
|
||||
### 3. `content-negotiation` 是干什么的?(给学生讲)
|
||||
`ktor-client-content-negotiation` + `ktor-serialization-kotlinx-json` 这两个依赖,
|
||||
就是让 Ktor 能把接口返回的 JSON 自动反序列化成 Kotlin 数据类(例如 `List<Product>`)。
|
||||
|
||||
对应代码就是:
|
||||
|
||||
```kotlin
|
||||
install(ContentNegotiation) {
|
||||
json(Json {
|
||||
ignoreUnknownKeys = true
|
||||
isLenient = true
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
如果不加这两个依赖,`body<List<Product>>()` 这类写法会失败(无法自动解析 JSON)。
|
||||
|
||||
### 4. 为什么是 `libs.ktor.client.content.negotiation`?
|
||||
这是 **Version Catalog(`libs.versions.toml`)自动生成 accessor** 的规则。
|
||||
|
||||
例如你在 TOML 里定义:
|
||||
|
||||
Reference in new issue
Block a user