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
相关产品推荐
相关产品推荐

