Kotlin中从流解码JSON

huangapple go评论48阅读模式
英文:

JSON decoding from stream in Kotlin

问题

抱歉,你的请求中包含代码部分,根据你的要求,我将提供代码部分的翻译:

我已经设置了一个服务器来通过本地主机端口发送消息我试图解码服务器发送的序列化JSON消息并出现了以下错误

错误解码消息kotlinx.serialization.json.internal.JsonDecodingException: 偏移55处出现意外的JSON令牌预期在解析后出现EOF但实际是在路径$中出现了
JSON输入.....mber":13,"Timestamp":5769784} ......

Racer State消息的JSON格式如下{SensorId:,RacerBibNumber:,Timestamp:}其中值是字段值的字符字符串表示我还尝试将我的RacerStatus类更改为接受String而不是Int但出现了类似的错误我在这里是否漏掉了什么错误中缺少的符号无法复制所以我知道它不是UTF-8

我还添加了以下代码

val inputString = bytes.toString(Charsets.UTF_8)
println("Received input: $inputString")

这会得到以下结果:
Received input: ```{"SensorId":0,"RacerBibNumber":5254,"Timestamp":3000203}  ```,末尾带有大量不相关的符号。

```@Serializable
data class RacerStatus(
    var SensorId: Int,
    var RacerBibNumber: Int,
    var Timestamp: Int
) {

    fun encode(): ByteArray {
        return Json.encodeToString(serializer(), this).toByteArray()
    }

    companion object {
        fun decode(bytes: ByteArray): RacerStatus {
            print(bytes[0])

            try {
                val mstream = ByteArrayInputStream(bytes)
                return Json.decodeFromStream<RacerStatus>(mstream)
            } catch (e: SerializationException) {
                println("Error decoding message: $e")
                return RacerStatus(0, 0, 0)
            }

//            return Json.decodeFromString(serializer(), mstream.readBytes().toString())
        }
    }
}

希望这些翻译对你有帮助。如果你需要更多帮助,请随时提问。

英文:

I have a server set up to send messages over a local host port. I am trying to decode the serialized json messages sent by the server and get this error.

Error decoding message: kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 55: Expected EOF after parsing, but had   instead at path: $
JSON input: .....mber":13,"Timestamp":5769784}                               .....

The Racer State messages are formatted in JSON as follows: { “SensorId”: “value”, “RacerBibNumber” : “value”, “Timestamp” : “value” }, where the value’s are character string representations of the field values. I have also tried changing my RacerStatus Class to take String instead of Int but to a similar error. Am I missing something here? The symbol that is missing in the error was not able to be copied over so I know it's not UTF-8.

I have also added

val inputString = bytes.toString(Charsets.UTF_8)
println("Received input: $inputString")

This gets
Received input: {"SensorId":0,"RacerBibNumber":5254,"Timestamp":3000203}
with a bunch of extraneous symbols at the end.

data class RacerStatus(
    var SensorId: Int,
    var RacerBibNumber: Int,
    var Timestamp: Int
) {


    fun encode(): ByteArray {
        return Json.encodeToString(serializer(), this).toByteArray()
    }

    companion object {
        fun decode(bytes: ByteArray): RacerStatus {
            print(bytes[0])

            try {
                val mstream = ByteArrayInputStream(bytes)
                return Json.decodeFromStream<RacerStatus>(mstream)
            } catch (e: SerializationException) {
                println("Error decoding message: $e")
                return RacerStatus(0, 0, 0)
            }

//            return Json.decodeFromString(serializer(), mstream.readBytes().toString())
        }
    }
}

答案1

得分: 0

我找到了答案解决我的问题。我添加了一个正则表达式,以包括我知道我的 JSON 包含的 JSON 组件。

val str = bytes.toString(Charsets.UTF_8)
val re = Regex("[^A-Za-z0-9{}:,\"]")
return Json.decodeFromString<RacerStatus>(re.replace(str, ""))

我以为 Charsets.UTF_8 会去除杂字符,但实际上没有。是否有更直观的解决方案?另外,是否有一个可以覆盖 JSON 中所有可能值的正则表达式?

英文:

So I found an answer to my question. I added a regex to include just the json components I know my json contains.

val str = bytes.toString(Charsets.UTF_8)
val re = Regex(&quot;[^A-Za-z0-9{}:,\&quot;\&quot;]&quot;)
                return Json.decodeFromString&lt;RacerStatus&gt;(re.replace(str,&quot;&quot;))

I thought that Charsets.UTF_8 would remove the misc characters but it did not. Is there a more intiuative solution? Also is there a regex that would cover all possible values in json?

huangapple
  • 本文由 发表于 2023年2月14日 05:36:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441423.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定