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

Kotlin中使用Postman调用STOMP消息的反序列化异常排查

问题:WebSocket消息无法反序列化为Kotlin数据类

现有控制器代码

@MessageMapping("/hello")
@SendTo("/topic/greetings")
@Throws(Exception::class)
fun greeting(message: TestMessage): Greeting {

报错信息

调用接口发送消息时触发以下反序列化错误:

Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.gleason.love_monkey.model.TestMessage` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); line: 1, column: 2]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63) ~[jackson-databind-2.18.2.jar:2.18.2]
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1754) ~[jackson-databind-2.18.2.jar:2.18.2]

临时调试方案

我把方法参数改为Any,尝试查看原始消息内容:

fun greeting(message: Any): Greeting {
    val jsonString: String
    // 记录传入消息
    if (message is ByteArray) {
        jsonString = byteArrayToString(message)
    } else {
        jsonString = objectMapper.writeValueAsString(message)
    }
    logger.info("Received message: $jsonString")

此时日志能正确输出消息内容,格式是合法的JSON:

2025-01-31T18:40:40.006-05:00  INFO 49504 --- [love-monkey] [nboundChannel-1] o.g.l.controller.WebsocketController     : Received message: {"name":"me"}

数据类定义

data class TestMessage(val name: String)

更新:手动反序列化仍失败

我添加了手动反序列化逻辑,并且给ObjectMapper注册了Kotlin模块,但依旧抛出相同的反序列化异常:

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
...
private val objectMapper = ObjectMapper().registerKotlinModule()
...
val jsonString: String
// 记录传入消息
if (message is ByteArray) {
    jsonString = byteArrayToString(message)
} else {
    jsonString = objectMapper.writeValueAsString(message)
}
logger.info("Received message: $jsonString")

// 反序列化前记录JSON字符串
logger.info("JSON string to be deserialized: ${jsonString.trim()}")

val testMessage: TestMessage = objectMapper.readValue(jsonString.trim(), TestMessage::class.java)

调试时确认传入ObjectMapper的JSON字符串完全正确,但报错依旧。

原始发送的消息帧

我用Postman发送的消息帧内容如下:

SEND
destination:/app/hello
content-length:19
content-type:application/json

{"name":"Me"}

我遗漏了什么?如何在使用Postman的同时让控制器正确接收并类型化TestMessage参数?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 17:25:58