gpt4 book ai didi

json - 如何使用 uint8 将 json 解码为 struct

转载 作者:行者123 更新时间:2023-12-01 22:25:58 24 4
gpt4 key购买 nike

如何将 json 解码为包含 uint8 的结构?我收到错误消息 json: cannot unmarshal object into Go struct field A.test of type uint8
在我的结构中,我有

type A struct {
Test uint8 `json:"test omitempty" bson:"test"`
}

我将 struct A 插入到 mongo 中,然后我成功地做了一个 mongo 查找并打印出 struct A 对应的集合。我可以执行 bson.MarshalExtJSON 将 bson 转换为 json,然后当我执行 json.Unmarshal 将 json 转换为 struct A 时,这就是我失败的地方。

这是一个重现问题的示例 golang playground。我不明白为什么这会失败?我如何解决它?

https://play.golang.org/p/0HOAxsu166j

我看到 unmarshal 使用“float64,用于 JSON 数字”,但我无法让 float64 而不是 uint8 工作

最佳答案

感谢@Brits 的评论,我发现当我调用 bson.MarshalExtJSON 时,我得到了extendedJson。 json.Unmarshal() 无法像 {"$numberInt":"52"} 那样读取extendedJson所以这就是它失败的原因。

所以要解决它,我正在使用 bson.UnmarshalExtJSON()而不是 json.Unmarshal()能够将extendedJSON解码到结构中

关于json - 如何使用 uint8 将 json 解码为 struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59959492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com