You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot接口布尔值序列化问题及Ktor客户端适配咨询

解决Kotlin多平台Ktor客户端与Spring Boot布尔值序列化/反序列化问题

方案一:修改Spring Boot接口返回JSON对象

方式1:自定义包装类

创建一个简单的响应包装类,把布尔值封装成JSON对象:

data class BooleanResponse(val value: Boolean)

然后修改接口的返回类型:

@GetMapping("/api/v1/user/existsByUsername/{username}", produces = [MediaType.APPLICATION_JSON_VALUE])
@ResponseBody
fun userExistsByUsername(@PathVariable("username") username: String): ResponseEntity<BooleanResponse> {
    val exists = userService.usernameExists(username)
    return ResponseEntity.status(HttpStatus.OK).body(BooleanResponse(exists))
}

修改后接口会返回{"value": true}格式的JSON对象,Ktor客户端可以正常反序列化。

方式2:用Map临时包装

如果不想额外创建类,也可以直接用Map包装布尔值返回:

@GetMapping("/api/v1/user/existsByUsername/{username}", produces = [MediaType.APPLICATION_JSON_VALUE])
@ResponseBody
fun userExistsByUsername(@PathVariable("username") username: String): ResponseEntity<Map<String, Boolean>> {
    val exists = userService.usernameExists(username)
    return ResponseEntity.status(HttpStatus.OK).body(mapOf("exists" to exists))
}

这种方式会返回{"exists": true},同样符合标准JSON对象格式。

方案二:配置Ktor客户端支持基础类型裸值反序列化

如果不想改动后端代码,可以调整Ktor客户端的序列化配置,让它能解析裸值类型。假设你使用的是Kotlinx Serialization,配置如下:

install(ContentNegotiation) {
    json(Json {
        // 允许解析非对象/数组的裸JSON值
        isLenient = true
        // 可根据需求添加其他配置,比如忽略未知字段
        ignoreUnknownKeys = true
    })
}

之后发起请求时,直接指定反序列化为Boolean类型即可:

val exists = client.get("http://your-server/api/v1/user/existsByUsername/test") {
}.body<Boolean>()

内容的提问来源于stack exchange,提问作者padmalcom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 04:27:02